/******************************************************************************
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/code/electron-utility/sharedProcess/sharedProcessMain.js
import { hostname as hostname2, release as release3 } from "os";

// 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;
}
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 $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 $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 $Ub(array) {
  return array.filter((e) => !!e);
}
function $Yb(obj) {
  return Array.isArray(obj) && obj.length > 0;
}
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/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, type2) {
  if (!condition) {
    throw new Error(type2 ? `Unexpected type, expected '${type2}'` : "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";
}

// 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/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/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/map.js
var _a2;
var _b;
var _c;
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/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/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/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(platform) {
  switch (platform) {
    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 $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);

// 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, merge2, initial, disposable) {
    let output = initial;
    return map(event, (e) => {
      output = merge2(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, merge2, delay = 100, leading = false, flushOnListenerRemove = false, leakWarningThreshold, disposable) {
    let subscription;
    let output = void 0;
    let handle2 = void 0;
    let numDebouncedCalls = 0;
    let doFire;
    const options = {
      leakWarningThreshold,
      onWillAddFirstListener() {
        subscription = event((cur) => {
          numDebouncedCalls++;
          output = merge2(output, cur);
          if (leading && !handle2) {
            emitter.fire(output);
            output = void 0;
          }
          doFire = () => {
            const _output = output;
            output = void 0;
            handle2 = void 0;
            if (!leading || numDebouncedCalls > 1) {
              emitter.fire(_output);
            }
            numDebouncedCalls = 0;
          };
          if (typeof delay === "number") {
            clearTimeout(handle2);
            handle2 = setTimeout(doFire, delay);
          } else {
            if (handle2 === void 0) {
              handle2 = 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(merge2, initial) {
      let last = initial;
      this.f.push((v) => {
        last = merge2(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((resolve) => once(event)(resolve));
  }
  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 dispose = () => {
      if (this.g) {
        this.o(e);
      }
      const idx = this.h.indexOf(e);
      this.h.splice(idx, 1);
    };
    return $8c($qb(dispose));
  }
  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/cancellation.js
var shortcutEvent = Object.freeze(function(callback, context) {
  const handle2 = setTimeout(callback.bind(context), 0);
  return { dispose() {
    clearTimeout(handle2);
  } };
});
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(code) {
  return code >= 97 && code <= 122;
}
function $Yf(code) {
  return code >= 65 && code <= 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 */
);
function $qg(str) {
  return str.charAt(0).toUpperCase() + str.slice(1);
}
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/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 type2 = name.indexOf(".") !== -1 ? "property" : "argument";
    let msg = `The "${name}" ${type2} ${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(code) {
  return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH;
}
function isPosixPathSeparator(code) {
  return code === CHAR_FORWARD_SLASH;
}
function isWindowsDeviceRoot(code) {
  return code >= CHAR_UPPERCASE_A && code <= CHAR_UPPERCASE_Z || code >= CHAR_LOWERCASE_A && code <= CHAR_LOWERCASE_Z;
}
function normalizeString(path2, allowAboveRoot, separator, isPathSeparator2) {
  let res = "";
  let lastSegmentLength = 0;
  let lastSlash = -1;
  let dots = 0;
  let code = 0;
  for (let i = 0; i <= path2.length; ++i) {
    if (i < path2.length) {
      code = path2.charCodeAt(i);
    } else if (isPathSeparator2(code)) {
      break;
    } else {
      code = CHAR_FORWARD_SLASH;
    }
    if (isPathSeparator2(code)) {
      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}${path2.slice(lastSlash + 1, i)}`;
        } else {
          res = path2.slice(lastSlash + 1, i);
        }
        lastSegmentLength = i - lastSlash - 1;
      }
      lastSlash = i;
      dots = 0;
    } else if (code === 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 path2;
      if (i >= 0) {
        path2 = pathSegments[i];
        validateString(path2, `paths[${i}]`);
        if (path2.length === 0) {
          continue;
        }
      } else if (resolvedDevice.length === 0) {
        path2 = cwd();
      } else {
        path2 = env[`=${resolvedDevice}`] || cwd();
        if (path2 === void 0 || path2.slice(0, 2).toLowerCase() !== resolvedDevice.toLowerCase() && path2.charCodeAt(2) === CHAR_BACKWARD_SLASH) {
          path2 = `${resolvedDevice}\\`;
        }
      }
      const len = path2.length;
      let rootEnd = 0;
      let device = "";
      let isAbsolute = false;
      const code = path2.charCodeAt(0);
      if (len === 1) {
        if (isPathSeparator(code)) {
          rootEnd = 1;
          isAbsolute = true;
        }
      } else if (isPathSeparator(code)) {
        isAbsolute = true;
        if (isPathSeparator(path2.charCodeAt(1))) {
          let j = 2;
          let last = j;
          while (j < len && !isPathSeparator(path2.charCodeAt(j))) {
            j++;
          }
          if (j < len && j !== last) {
            const firstPart = path2.slice(last, j);
            last = j;
            while (j < len && isPathSeparator(path2.charCodeAt(j))) {
              j++;
            }
            if (j < len && j !== last) {
              last = j;
              while (j < len && !isPathSeparator(path2.charCodeAt(j))) {
                j++;
              }
              if (j === len || j !== last) {
                device = `\\\\${firstPart}\\${path2.slice(last, j)}`;
                rootEnd = j;
              }
            }
          }
        } else {
          rootEnd = 1;
        }
      } else if (isWindowsDeviceRoot(code) && path2.charCodeAt(1) === CHAR_COLON) {
        device = path2.slice(0, 2);
        rootEnd = 2;
        if (len > 2 && isPathSeparator(path2.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 = `${path2.slice(rootEnd)}\\${resolvedTail}`;
        resolvedAbsolute = isAbsolute;
        if (isAbsolute && resolvedDevice.length > 0) {
          break;
        }
      }
    }
    resolvedTail = normalizeString(resolvedTail, !resolvedAbsolute, "\\", isPathSeparator);
    return resolvedAbsolute ? `${resolvedDevice}\\${resolvedTail}` : `${resolvedDevice}${resolvedTail}` || ".";
  },
  normalize(path2) {
    validateString(path2, "path");
    const len = path2.length;
    if (len === 0) {
      return ".";
    }
    let rootEnd = 0;
    let device;
    let isAbsolute = false;
    const code = path2.charCodeAt(0);
    if (len === 1) {
      return isPosixPathSeparator(code) ? "\\" : path2;
    }
    if (isPathSeparator(code)) {
      isAbsolute = true;
      if (isPathSeparator(path2.charCodeAt(1))) {
        let j = 2;
        let last = j;
        while (j < len && !isPathSeparator(path2.charCodeAt(j))) {
          j++;
        }
        if (j < len && j !== last) {
          const firstPart = path2.slice(last, j);
          last = j;
          while (j < len && isPathSeparator(path2.charCodeAt(j))) {
            j++;
          }
          if (j < len && j !== last) {
            last = j;
            while (j < len && !isPathSeparator(path2.charCodeAt(j))) {
              j++;
            }
            if (j === len) {
              return `\\\\${firstPart}\\${path2.slice(last)}\\`;
            }
            if (j !== last) {
              device = `\\\\${firstPart}\\${path2.slice(last, j)}`;
              rootEnd = j;
            }
          }
        }
      } else {
        rootEnd = 1;
      }
    } else if (isWindowsDeviceRoot(code) && path2.charCodeAt(1) === CHAR_COLON) {
      device = path2.slice(0, 2);
      rootEnd = 2;
      if (len > 2 && isPathSeparator(path2.charCodeAt(2))) {
        isAbsolute = true;
        rootEnd = 3;
      }
    }
    let tail = rootEnd < len ? normalizeString(path2.slice(rootEnd), !isAbsolute, "\\", isPathSeparator) : "";
    if (tail.length === 0 && !isAbsolute) {
      tail = ".";
    }
    if (tail.length > 0 && isPathSeparator(path2.charCodeAt(len - 1))) {
      tail += "\\";
    }
    if (device === void 0) {
      return isAbsolute ? `\\${tail}` : tail;
    }
    return isAbsolute ? `${device}\\${tail}` : `${device}${tail}`;
  },
  isAbsolute(path2) {
    validateString(path2, "path");
    const len = path2.length;
    if (len === 0) {
      return false;
    }
    const code = path2.charCodeAt(0);
    return isPathSeparator(code) || // Possible device root
    len > 2 && isWindowsDeviceRoot(code) && path2.charCodeAt(1) === CHAR_COLON && isPathSeparator(path2.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(path2) {
    if (typeof path2 !== "string" || path2.length === 0) {
      return path2;
    }
    const resolvedPath = $rc.resolve(path2);
    if (resolvedPath.length <= 2) {
      return path2;
    }
    if (resolvedPath.charCodeAt(0) === CHAR_BACKWARD_SLASH) {
      if (resolvedPath.charCodeAt(1) === CHAR_BACKWARD_SLASH) {
        const code = resolvedPath.charCodeAt(2);
        if (code !== CHAR_QUESTION_MARK && code !== 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 path2;
  },
  dirname(path2) {
    validateString(path2, "path");
    const len = path2.length;
    if (len === 0) {
      return ".";
    }
    let rootEnd = -1;
    let offset = 0;
    const code = path2.charCodeAt(0);
    if (len === 1) {
      return isPathSeparator(code) ? path2 : ".";
    }
    if (isPathSeparator(code)) {
      rootEnd = offset = 1;
      if (isPathSeparator(path2.charCodeAt(1))) {
        let j = 2;
        let last = j;
        while (j < len && !isPathSeparator(path2.charCodeAt(j))) {
          j++;
        }
        if (j < len && j !== last) {
          last = j;
          while (j < len && isPathSeparator(path2.charCodeAt(j))) {
            j++;
          }
          if (j < len && j !== last) {
            last = j;
            while (j < len && !isPathSeparator(path2.charCodeAt(j))) {
              j++;
            }
            if (j === len) {
              return path2;
            }
            if (j !== last) {
              rootEnd = offset = j + 1;
            }
          }
        }
      }
    } else if (isWindowsDeviceRoot(code) && path2.charCodeAt(1) === CHAR_COLON) {
      rootEnd = len > 2 && isPathSeparator(path2.charCodeAt(2)) ? 3 : 2;
      offset = rootEnd;
    }
    let end = -1;
    let matchedSlash = true;
    for (let i = len - 1; i >= offset; --i) {
      if (isPathSeparator(path2.charCodeAt(i))) {
        if (!matchedSlash) {
          end = i;
          break;
        }
      } else {
        matchedSlash = false;
      }
    }
    if (end === -1) {
      if (rootEnd === -1) {
        return ".";
      }
      end = rootEnd;
    }
    return path2.slice(0, end);
  },
  basename(path2, suffix) {
    if (suffix !== void 0) {
      validateString(suffix, "suffix");
    }
    validateString(path2, "path");
    let start = 0;
    let end = -1;
    let matchedSlash = true;
    let i;
    if (path2.length >= 2 && isWindowsDeviceRoot(path2.charCodeAt(0)) && path2.charCodeAt(1) === CHAR_COLON) {
      start = 2;
    }
    if (suffix !== void 0 && suffix.length > 0 && suffix.length <= path2.length) {
      if (suffix === path2) {
        return "";
      }
      let extIdx = suffix.length - 1;
      let firstNonSlashEnd = -1;
      for (i = path2.length - 1; i >= start; --i) {
        const code = path2.charCodeAt(i);
        if (isPathSeparator(code)) {
          if (!matchedSlash) {
            start = i + 1;
            break;
          }
        } else {
          if (firstNonSlashEnd === -1) {
            matchedSlash = false;
            firstNonSlashEnd = i + 1;
          }
          if (extIdx >= 0) {
            if (code === suffix.charCodeAt(extIdx)) {
              if (--extIdx === -1) {
                end = i;
              }
            } else {
              extIdx = -1;
              end = firstNonSlashEnd;
            }
          }
        }
      }
      if (start === end) {
        end = firstNonSlashEnd;
      } else if (end === -1) {
        end = path2.length;
      }
      return path2.slice(start, end);
    }
    for (i = path2.length - 1; i >= start; --i) {
      if (isPathSeparator(path2.charCodeAt(i))) {
        if (!matchedSlash) {
          start = i + 1;
          break;
        }
      } else if (end === -1) {
        matchedSlash = false;
        end = i + 1;
      }
    }
    if (end === -1) {
      return "";
    }
    return path2.slice(start, end);
  },
  extname(path2) {
    validateString(path2, "path");
    let start = 0;
    let startDot = -1;
    let startPart = 0;
    let end = -1;
    let matchedSlash = true;
    let preDotState = 0;
    if (path2.length >= 2 && path2.charCodeAt(1) === CHAR_COLON && isWindowsDeviceRoot(path2.charCodeAt(0))) {
      start = startPart = 2;
    }
    for (let i = path2.length - 1; i >= start; --i) {
      const code = path2.charCodeAt(i);
      if (isPathSeparator(code)) {
        if (!matchedSlash) {
          startPart = i + 1;
          break;
        }
        continue;
      }
      if (end === -1) {
        matchedSlash = false;
        end = i + 1;
      }
      if (code === 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 path2.slice(startDot, end);
  },
  format: _format2.bind(null, "\\"),
  parse(path2) {
    validateString(path2, "path");
    const ret = { root: "", dir: "", base: "", ext: "", name: "" };
    if (path2.length === 0) {
      return ret;
    }
    const len = path2.length;
    let rootEnd = 0;
    let code = path2.charCodeAt(0);
    if (len === 1) {
      if (isPathSeparator(code)) {
        ret.root = ret.dir = path2;
        return ret;
      }
      ret.base = ret.name = path2;
      return ret;
    }
    if (isPathSeparator(code)) {
      rootEnd = 1;
      if (isPathSeparator(path2.charCodeAt(1))) {
        let j = 2;
        let last = j;
        while (j < len && !isPathSeparator(path2.charCodeAt(j))) {
          j++;
        }
        if (j < len && j !== last) {
          last = j;
          while (j < len && isPathSeparator(path2.charCodeAt(j))) {
            j++;
          }
          if (j < len && j !== last) {
            last = j;
            while (j < len && !isPathSeparator(path2.charCodeAt(j))) {
              j++;
            }
            if (j === len) {
              rootEnd = j;
            } else if (j !== last) {
              rootEnd = j + 1;
            }
          }
        }
      }
    } else if (isWindowsDeviceRoot(code) && path2.charCodeAt(1) === CHAR_COLON) {
      if (len <= 2) {
        ret.root = ret.dir = path2;
        return ret;
      }
      rootEnd = 2;
      if (isPathSeparator(path2.charCodeAt(2))) {
        if (len === 3) {
          ret.root = ret.dir = path2;
          return ret;
        }
        rootEnd = 3;
      }
    }
    if (rootEnd > 0) {
      ret.root = path2.slice(0, rootEnd);
    }
    let startDot = -1;
    let startPart = rootEnd;
    let end = -1;
    let matchedSlash = true;
    let i = path2.length - 1;
    let preDotState = 0;
    for (; i >= rootEnd; --i) {
      code = path2.charCodeAt(i);
      if (isPathSeparator(code)) {
        if (!matchedSlash) {
          startPart = i + 1;
          break;
        }
        continue;
      }
      if (end === -1) {
        matchedSlash = false;
        end = i + 1;
      }
      if (code === 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 = path2.slice(startPart, end);
      } else {
        ret.name = path2.slice(startPart, startDot);
        ret.base = path2.slice(startPart, end);
        ret.ext = path2.slice(startDot, end);
      }
    }
    if (startPart > 0 && startPart !== rootEnd) {
      ret.dir = path2.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 path2 = i >= 0 ? pathSegments[i] : posixCwd();
      validateString(path2, `paths[${i}]`);
      if (path2.length === 0) {
        continue;
      }
      resolvedPath = `${path2}/${resolvedPath}`;
      resolvedAbsolute = path2.charCodeAt(0) === CHAR_FORWARD_SLASH;
    }
    resolvedPath = normalizeString(resolvedPath, !resolvedAbsolute, "/", isPosixPathSeparator);
    if (resolvedAbsolute) {
      return `/${resolvedPath}`;
    }
    return resolvedPath.length > 0 ? resolvedPath : ".";
  },
  normalize(path2) {
    validateString(path2, "path");
    if (path2.length === 0) {
      return ".";
    }
    const isAbsolute = path2.charCodeAt(0) === CHAR_FORWARD_SLASH;
    const trailingSeparator = path2.charCodeAt(path2.length - 1) === CHAR_FORWARD_SLASH;
    path2 = normalizeString(path2, !isAbsolute, "/", isPosixPathSeparator);
    if (path2.length === 0) {
      if (isAbsolute) {
        return "/";
      }
      return trailingSeparator ? "./" : ".";
    }
    if (trailingSeparator) {
      path2 += "/";
    }
    return isAbsolute ? `/${path2}` : path2;
  },
  isAbsolute(path2) {
    validateString(path2, "path");
    return path2.length > 0 && path2.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(path2) {
    return path2;
  },
  dirname(path2) {
    validateString(path2, "path");
    if (path2.length === 0) {
      return ".";
    }
    const hasRoot = path2.charCodeAt(0) === CHAR_FORWARD_SLASH;
    let end = -1;
    let matchedSlash = true;
    for (let i = path2.length - 1; i >= 1; --i) {
      if (path2.charCodeAt(i) === CHAR_FORWARD_SLASH) {
        if (!matchedSlash) {
          end = i;
          break;
        }
      } else {
        matchedSlash = false;
      }
    }
    if (end === -1) {
      return hasRoot ? "/" : ".";
    }
    if (hasRoot && end === 1) {
      return "//";
    }
    return path2.slice(0, end);
  },
  basename(path2, suffix) {
    if (suffix !== void 0) {
      validateString(suffix, "ext");
    }
    validateString(path2, "path");
    let start = 0;
    let end = -1;
    let matchedSlash = true;
    let i;
    if (suffix !== void 0 && suffix.length > 0 && suffix.length <= path2.length) {
      if (suffix === path2) {
        return "";
      }
      let extIdx = suffix.length - 1;
      let firstNonSlashEnd = -1;
      for (i = path2.length - 1; i >= 0; --i) {
        const code = path2.charCodeAt(i);
        if (code === CHAR_FORWARD_SLASH) {
          if (!matchedSlash) {
            start = i + 1;
            break;
          }
        } else {
          if (firstNonSlashEnd === -1) {
            matchedSlash = false;
            firstNonSlashEnd = i + 1;
          }
          if (extIdx >= 0) {
            if (code === suffix.charCodeAt(extIdx)) {
              if (--extIdx === -1) {
                end = i;
              }
            } else {
              extIdx = -1;
              end = firstNonSlashEnd;
            }
          }
        }
      }
      if (start === end) {
        end = firstNonSlashEnd;
      } else if (end === -1) {
        end = path2.length;
      }
      return path2.slice(start, end);
    }
    for (i = path2.length - 1; i >= 0; --i) {
      if (path2.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 path2.slice(start, end);
  },
  extname(path2) {
    validateString(path2, "path");
    let startDot = -1;
    let startPart = 0;
    let end = -1;
    let matchedSlash = true;
    let preDotState = 0;
    for (let i = path2.length - 1; i >= 0; --i) {
      const code = path2.charCodeAt(i);
      if (code === CHAR_FORWARD_SLASH) {
        if (!matchedSlash) {
          startPart = i + 1;
          break;
        }
        continue;
      }
      if (end === -1) {
        matchedSlash = false;
        end = i + 1;
      }
      if (code === 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 path2.slice(startDot, end);
  },
  format: _format2.bind(null, "/"),
  parse(path2) {
    validateString(path2, "path");
    const ret = { root: "", dir: "", base: "", ext: "", name: "" };
    if (path2.length === 0) {
      return ret;
    }
    const isAbsolute = path2.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 = path2.length - 1;
    let preDotState = 0;
    for (; i >= start; --i) {
      const code = path2.charCodeAt(i);
      if (code === CHAR_FORWARD_SLASH) {
        if (!matchedSlash) {
          startPart = i + 1;
          break;
        }
        continue;
      }
      if (end === -1) {
        matchedSlash = false;
        end = i + 1;
      }
      if (code === 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 = path2.slice(start2, end);
      } else {
        ret.name = path2.slice(start2, startDot);
        ret.base = path2.slice(start2, end);
        ret.ext = path2.slice(startDot, end);
      }
    }
    if (startPart > 0) {
      ret.dir = path2.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, path2) {
  switch (scheme) {
    case "https":
    case "http":
    case "file":
      if (!path2) {
        path2 = _slash;
      } else if (path2[0] !== _slash) {
        path2 = _slash + path2;
      }
      break;
  }
  return path2;
}
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, path2, 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, path2 || _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: path2, 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 (path2 === void 0) {
      path2 = this.path;
    } else if (path2 === null) {
      path2 = _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 && path2 === this.path && query === this.query && fragment === this.fragment) {
      return this;
    }
    return new Uri(scheme, authority, path2, 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(path2) {
    let authority = _empty;
    if ($l) {
      path2 = path2.replace(/\\/g, _slash);
    }
    if (path2[0] === _slash && path2[1] === _slash) {
      const idx = path2.indexOf(_slash, 2);
      if (idx === -1) {
        authority = path2.substring(2);
        path2 = _slash;
      } else {
        authority = path2.substring(2, idx);
        path2 = path2.substring(idx) || _slash;
      }
    }
    return new Uri("file", authority, path2, _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 code = uriComponent.charCodeAt(pos);
    if (code >= 97 && code <= 122 || code >= 65 && code <= 90 || code >= 48 && code <= 57 || code === 45 || code === 46 || code === 95 || code === 126 || isPath && code === 47 || isAuthority && code === 91 || isAuthority && code === 93 || isAuthority && code === 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[code];
      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(path2) {
  let res = void 0;
  for (let pos = 0; pos < path2.length; pos++) {
    const code = path2.charCodeAt(pos);
    if (code === 35 || code === 63) {
      if (res === void 0) {
        res = path2.substr(0, pos);
      }
      res += encodeTable[code];
    } else {
      if (res !== void 0) {
        res += path2[pos];
      }
    }
  }
  return res !== void 0 ? res : path2;
}
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: path2, 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 (path2) {
    if (path2.length >= 3 && path2.charCodeAt(0) === 47 && path2.charCodeAt(2) === 58) {
      const code = path2.charCodeAt(1);
      if (code >= 65 && code <= 90) {
        path2 = `/${String.fromCharCode(code + 32)}:${path2.substr(3)}`;
      }
    } else if (path2.length >= 2 && path2.charCodeAt(1) === 58) {
      const code = path2.charCodeAt(0);
      if (code >= 65 && code <= 90) {
        path2 = `${String.fromCharCode(code + 32)}:${path2.substr(2)}`;
      }
    }
    res += encoder(path2, 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/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 = {}));
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/extpath.js
function $Rg(code) {
  return code === 47 || code === 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(path2, sep2 = $sc.sep) {
  if (!path2) {
    return "";
  }
  const len = path2.length;
  const firstLetter = path2.charCodeAt(0);
  if ($Rg(firstLetter)) {
    if ($Rg(path2.charCodeAt(1))) {
      if (!$Rg(path2.charCodeAt(2))) {
        let pos2 = 3;
        const start = pos2;
        for (; pos2 < len; pos2++) {
          if ($Rg(path2.charCodeAt(pos2))) {
            break;
          }
        }
        if (start !== pos2 && !$Rg(path2.charCodeAt(pos2 + 1))) {
          pos2 += 1;
          for (; pos2 < len; pos2++) {
            if ($Rg(path2.charCodeAt(pos2))) {
              return path2.slice(0, pos2 + 1).replace(/[\\/]/g, sep2);
            }
          }
        }
      }
    }
    return sep2;
  } else if ($Zg(firstLetter)) {
    if (path2.charCodeAt(1) === 58) {
      if ($Rg(path2.charCodeAt(2))) {
        return path2.slice(0, 2) + sep2;
      } else {
        return path2.slice(0, 2);
      }
    }
  }
  let pos = path2.indexOf("://");
  if (pos !== -1) {
    pos += 3;
    for (; pos < len; pos++) {
      if ($Rg(path2.charCodeAt(pos))) {
        return path2.slice(0, pos + 1);
      }
    }
  }
  return "";
}
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 $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(path2) {
  const pathNormalized = $tc(path2);
  if ($l) {
    if (path2.length > 3) {
      return false;
    }
    return $4g(pathNormalized) && (path2.length === 2 || pathNormalized.charCodeAt(2) === 92);
  }
  return pathNormalized === $sc.sep;
}
function $4g(path2, isWindowsOS = $l) {
  if (isWindowsOS) {
    return $Zg(path2.charCodeAt(0)) && path2.charCodeAt(1) === 58;
  }
  return false;
}
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/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 dirname;
    if (resource.scheme === Schemas.file) {
      dirname = URI.file($yc($oh(resource))).path;
    } else {
      dirname = $sc.dirname(resource.path);
      if (resource.authority && dirname.length && dirname.charCodeAt(0) !== 47) {
        console.error(`dirname("${resource.toString})) resulted in a relative path`);
        dirname = "/";
      }
    }
    return resource.with({
      path: dirname
    });
  }
  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, path2) {
    if (base.scheme === Schemas.file) {
      const newURI = URI.file($wc($oh(base), path2));
      return base.with({
        authority: newURI.authority,
        path: newURI.path
      });
    }
    path2 = $Tg(path2);
    return base.with({
      path: $sc.resolve(base.path, path2)
    });
  }
  // --- 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((resolve, reject) => {
    const subscription = source.token.onCancellationRequested(() => {
      subscription.dispose();
      reject(new $fb());
    });
    Promise.resolve(thenable).then((value) => {
      subscription.dispose();
      source.dispose();
      resolve(value);
    }, (err) => {
      subscription.dispose();
      source.dispose();
      reject(err);
    });
  });
  return new class {
    cancel() {
      source.cancel();
      source.dispose();
    }
    then(resolve, reject) {
      return promise.then(resolve, reject);
    }
    catch(reject) {
      return this.then(void 0, reject);
    }
    finally(onfinally) {
      return promise.finally(onfinally);
    }
  }();
}
function $Sh() {
  let resolve;
  let reject;
  const promise = new Promise((res, rej) => {
    resolve = res;
    reject = rej;
  });
  return { promise, resolve, 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((resolve) => {
          this.a.then(onComplete, onComplete).then(resolve);
        });
      }
      return new Promise((resolve, reject) => {
        this.b.then(resolve, reject);
      });
    }
    this.a = promiseFactory();
    return new Promise((resolve, reject) => {
      this.a.then((result) => {
        this.a = null;
        resolve(result);
      }, (err) => {
        this.a = null;
        reject(err);
      });
    });
  }
  dispose() {
    this.f = true;
  }
};
var $Uh = class {
  constructor() {
    this.a = Promise.resolve(null);
  }
  queue(promiseTask) {
    return this.a = this.a.then(() => promiseTask(), () => promiseTask());
  }
};
var timeoutDeferred = (timeout, fn) => {
  let scheduled = true;
  const handle2 = setTimeout(() => {
    scheduled = false;
    fn();
  }, timeout);
  return {
    isTriggered: () => scheduled,
    dispose: () => {
      clearTimeout(handle2);
      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((resolve, reject) => {
        this.d = resolve;
        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((resolve, reject) => {
    const handle2 = setTimeout(() => {
      disposable.dispose();
      resolve();
    }, millis);
    const disposable = token.onCancellationRequested(() => {
      clearTimeout(handle2);
      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;
}
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 handle2 = targetWindow.requestIdleCallback(runner, typeof timeout === "number" ? { timeout } : void 0);
      let disposed = false;
      return {
        dispose() {
          if (disposed) {
            return;
          }
          disposed = true;
          targetWindow.cancelIdleCallback(handle2);
        }
      };
    };
  }
  $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((resolve) => {
      this.a(value);
      this.d = { outcome: 0, value };
      resolve();
    });
  }
  error(err) {
    return new Promise((resolve) => {
      this.b(err);
      this.d = { outcome: 1, value: err };
      resolve();
    });
  }
  cancel() {
    return this.error(new $fb());
  }
};
var Promises;
(function(Promises3) {
  async function settled(promises12) {
    let firstError = void 0;
    const result = await Promise.all(promises12.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 (resolve, reject) => {
      try {
        await bodyFn(resolve, 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(promises12) {
    return new _$ni(async (emitter) => {
      await Promise.all(promises12.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/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((resolve) => this.d.push(resolve));
      }
    }
  }
  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((resolve, reject) => {
    const chunks = [];
    $Ye(stream, {
      onData: (chunk) => {
        if (reducer) {
          chunks.push(chunk);
        }
      },
      onError: (error) => {
        if (reducer) {
          reject(error);
        } else {
          resolve(void 0);
        }
      },
      onEnd: () => {
        if (reducer) {
          resolve(reducer(chunks));
        } else {
          resolve(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((resolve, reject) => {
    const streamListeners = new $9c();
    const buffer = [];
    const dataListener = (chunk) => {
      buffer.push(chunk);
      if (buffer.length > maxChunks) {
        streamListeners.dispose();
        stream.pause();
        return resolve({ stream, buffer, ended: false });
      }
    };
    const errorListener = (error) => {
      streamListeners.dispose();
      return reject(error);
    };
    const endListener = () => {
      streamListeners.dispose();
      return resolve({ 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);
}
var base64Alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
var base64UrlSafeAlphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
function $of({ buffer }, padded = true, urlSafe = false) {
  const dictionary = urlSafe ? base64UrlSafeAlphabet : base64Alphabet;
  let output = "";
  const remainder = buffer.byteLength % 3;
  let i = 0;
  for (; i < buffer.byteLength - remainder; i += 3) {
    const a = buffer[i + 0];
    const b = buffer[i + 1];
    const c = buffer[i + 2];
    output += dictionary[a >>> 2];
    output += dictionary[(a << 4 | b >>> 4) & 63];
    output += dictionary[(b << 2 | c >>> 6) & 63];
    output += dictionary[c & 63];
  }
  if (remainder === 1) {
    const a = buffer[i + 0];
    output += dictionary[a >>> 2];
    output += dictionary[a << 4 & 63];
    if (padded) {
      output += "==";
    }
  } else if (remainder === 2) {
    const a = buffer[i + 0];
    const b = buffer[i + 1];
    output += dictionary[a >>> 2];
    output += dictionary[(a << 4 | b >>> 4) & 63];
    output += dictionary[b << 2 & 63];
    if (padded) {
      output += "=";
    }
  }
  return output;
}

// 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(type2) {
  switch (type2) {
    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(type2) {
  switch (type2) {
    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 type2 = reader.read(1).readUInt8(0);
  switch (type2) {
    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 type2 = header[0];
    switch (type2) {
      case 100:
        this.k?.logIncoming(message.byteLength, header[1], 1, `${requestTypeToStr(type2)}: ${header[2]}.${header[3]}`, body);
        return this.s({ type: type2, id: header[1], channelName: header[2], name: header[3], arg: body });
      case 102:
        this.k?.logIncoming(message.byteLength, header[1], 1, `${requestTypeToStr(type2)}: ${header[2]}.${header[3]}`, body);
        return this.t({ type: type2, id: header[1], channelName: header[2], name: header[3], arg: body });
      case 101:
        this.k?.logIncoming(message.byteLength, header[1], 1, `${requestTypeToStr(type2)}`);
        return this.u({ type: type2, id: header[1] });
      case 103:
        this.k?.logIncoming(message.byteLength, header[1], 1, `${requestTypeToStr(type2)}`);
        return this.u({ type: type2, id: header[1] });
    }
  }
  s(request2) {
    const channel = this.b.get(request2.channelName);
    if (!channel) {
      this.v(request2);
      return;
    }
    const cancellationTokenSource = new $Pe();
    let promise;
    try {
      promise = channel.call(this.j, request2.name, request2.arg, cancellationTokenSource.token);
    } catch (err) {
      promise = Promise.reject(err);
    }
    const id2 = request2.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(request2.id);
    });
    const disposable = $8c(() => cancellationTokenSource.cancel());
    this.d.set(request2.id, disposable);
  }
  t(request2) {
    const channel = this.b.get(request2.channelName);
    if (!channel) {
      this.v(request2);
      return;
    }
    const id2 = request2.id;
    const event = channel.listen(this.j, request2.name, request2.arg);
    const disposable = event((data) => this.m({
      id: id2,
      data,
      type: 204
      /* ResponseType.EventFire */
    }));
    this.d.set(request2.id, disposable);
  }
  u(request2) {
    const disposable = this.d.get(request2.id);
    if (disposable) {
      disposable.dispose();
      this.d.delete(request2.id);
    }
  }
  v(request2) {
    let pendingRequests = this.g.get(request2.channelName);
    if (!pendingRequests) {
      pendingRequests = [];
      this.g.set(request2.channelName, pendingRequests);
    }
    const timer = setTimeout(() => {
      console.error(`Unknown channel: ${request2.channelName}`);
      if (request2.type === 100) {
        this.m({
          id: request2.id,
          data: { name: "Unknown channel", message: `Channel name '${request2.channelName}' timed out after ${this.l}ms`, stack: void 0 },
          type: 202
          /* ResponseType.PromiseError */
        });
      }
    }, this.l);
    pendingRequests.push({ request: request2, timeoutTimer: timer });
  }
  w(channelName) {
    const requests = this.g.get(channelName);
    if (requests) {
      for (const request2 of requests) {
        clearTimeout(request2.timeoutTimer);
        switch (request2.request.type) {
          case 100:
            this.s(request2.request);
            break;
          case 102:
            this.t(request2.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 type2 = 100;
    const request2 = { id: id2, type: type2, 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(request2);
      };
      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 type2 = 102;
    const request2 = { id: id2, type: type2, 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(request2);
        });
      },
      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(request2) {
    switch (request2.type) {
      case 100:
      case 102: {
        const msgLength = this.q([request2.type, request2.id, request2.channelName, request2.name], request2.arg);
        this.j?.logOutgoing(msgLength, request2.id, 0, `${requestTypeToStr(request2.type)}: ${request2.channelName}.${request2.name}`, request2.arg);
        return;
      }
      case 101:
      case 103: {
        const msgLength = this.q([request2.type, request2.id]);
        this.j?.logOutgoing(msgLength, request2.id, 0, requestTypeToStr(request2.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 type2 = header[0];
    switch (type2) {
      case 200:
        this.j?.logIncoming(message.byteLength, 0, 0, responseTypeToStr(type2));
        return this.t({ type: header[0] });
      case 201:
      case 202:
      case 204:
      case 203:
        this.j?.logIncoming(message.byteLength, header[1], 0, responseTypeToStr(type2), 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, onDidClientDisconnect }) => {
      const onFirstMessage = Event.once(protocol.onMessage);
      this.j.add(onFirstMessage((msg) => {
        const reader = new $xi(msg);
        const ctx = $Ai(reader);
        const channelServer = new $Bi(protocol, ctx, ipcLogger, timeoutDelay);
        const channelClient = new $Ci(protocol, 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();
  }
};
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/sandbox/node/electronTypes.js
function $_Y(process2) {
  return !!process2.parentPort;
}

// out-build/vs/base/parts/ipc/node/ipc.mp.js
var Protocol = class {
  constructor(a) {
    this.a = a;
    this.onMessage = Event.fromNodeEventEmitter(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 $aZ = class _$aZ extends $Di {
  static b(filter) {
    $Ig($_Y(process), "Electron Utility Process");
    const onCreateMessageChannel = new $De();
    process.parentPort.on("message", (e) => {
      if (filter?.handledClientConnection(e)) {
        return;
      }
      const port = e.ports.at(0);
      if (port) {
        onCreateMessageChannel.fire(port);
      }
    });
    return Event.map(onCreateMessageChannel.event, (port) => {
      const protocol = new Protocol(port);
      const result = {
        protocol,
        // Not part of the standard spec, but in Electron we get a `close` event
        // when the other side closes. We can use this to detect disconnects
        // (https://github.com/electron/electron/blob/11-x-y/docs/api/message-port-main.md#event-close)
        onDidClientDisconnect: Event.fromNodeEventEmitter(port, "close")
      };
      return result;
    });
  }
  constructor(filter) {
    super(_$aZ.b(filter));
  }
};
function $bZ(port, message, callback) {
  const listener = (e) => {
    if (e.data === message) {
      port.removeListener("message", listener);
      callback();
    }
  };
  port.on("message", listener);
}

// out-build/vs/code/electron-utility/sharedProcess/contrib/codeCacheCleaner.js
import * as fs2 from "fs";

// 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(path2, mode = RimRafMode.UNLINK, moveToPath) {
  if ($3g(path2)) {
    throw new Error("rimraf - will refuse to recursively delete root");
  }
  if (mode === RimRafMode.UNLINK) {
    return rimrafUnlink(path2);
  }
  return rimrafMove(path2, moveToPath);
}
async function rimrafMove(path2, moveToPath = $8g(tmpdir())) {
  try {
    try {
      await fs.promises.rename(path2, moveToPath);
    } catch (error) {
      if (error.code === "ENOENT") {
        return;
      }
      return rimrafUnlink(path2);
    }
    rimrafUnlink(moveToPath).catch((error) => {
    });
  } catch (error) {
    if (error.code !== "ENOENT") {
      throw error;
    }
  }
}
async function rimrafUnlink(path2) {
  return fs.promises.rm(path2, { recursive: true, force: true, maxRetries: 3 });
}
async function readdir(path2, options) {
  return handleDirectoryChildren(await (options ? safeReaddirWithFileTypes(path2) : fs.promises.readdir(path2)));
}
async function safeReaddirWithFileTypes(path2) {
  try {
    return await fs.promises.readdir(path2, { withFileTypes: true });
  } catch (error) {
    console.warn("[node.js fs] readdir with filetypes failed with error: ", error);
  }
  const result = [];
  const children = await readdir(path2);
  for (const child of children) {
    let isFile = false;
    let isDirectory = false;
    let isSymbolicLink = false;
    try {
      const lstat = await fs.promises.lstat($vc(path2, 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;
}
var SymlinkSupport;
(function(SymlinkSupport2) {
  async function stat(path2) {
    let lstats;
    try {
      lstats = await fs.promises.lstat(path2);
      if (!lstats.isSymbolicLink()) {
        return { stat: lstats };
      }
    } catch (error) {
    }
    try {
      const stats = await fs.promises.stat(path2);
      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(path2));
          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(path2) {
    try {
      const { stat: stat2, symbolicLink } = await SymlinkSupport2.stat(path2);
      return stat2.isFile() && symbolicLink?.dangling !== true;
    } catch (error) {
    }
    return false;
  }
  SymlinkSupport2.existsFile = existsFile;
  async function existsDirectory(path2) {
    try {
      const { stat: stat2, symbolicLink } = await SymlinkSupport2.stat(path2);
      return stat2.isDirectory() && symbolicLink?.dangling !== true;
    } catch (error) {
    }
    return false;
  }
  SymlinkSupport2.existsDirectory = existsDirectory;
})(SymlinkSupport || (SymlinkSupport = {}));
var writeQueues = new $9h();
function writeFile2(path2, data, options) {
  return writeQueues.queueFor(URI.file(path2), () => {
    const ensuredOptions = ensureWriteOptions(options);
    return new Promise((resolve, reject) => doWriteFileAndFlush(path2, data, ensuredOptions, (error) => error ? reject(error) : resolve()));
  }, $rh);
}
var canFlush = true;
function configureFlushOnWrite(enabled) {
  canFlush = enabled;
}
function doWriteFileAndFlush(path2, data, options, callback) {
  if (!canFlush) {
    return fs.writeFile(path2, data, { mode: options.mode, flag: options.flag }, callback);
  }
  fs.open(path2, 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((resolve, reject) => {
        fs.read(fd, buffer, offset, length, position, (err, bytesRead, buffer2) => {
          if (err) {
            return reject(err);
          }
          return resolve({ bytesRead, buffer: buffer2 });
        });
      });
    };
  }
  get write() {
    return (fd, buffer, offset, length, position) => {
      return new Promise((resolve, reject) => {
        fs.write(fd, buffer, offset, length, position, (err, bytesWritten, buffer2) => {
          if (err) {
            return reject(err);
          }
          return resolve({ 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(path2) {
    try {
      await fs.promises.access(path2);
      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/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/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(type2) {
    this.f.push({ type: type2, 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/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/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(type2, message) {
    if (this.C(type2)) {
      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(type2) {
    return this.D().type === type2;
  }
  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 $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 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 $Ck = class extends $zk {
  constructor(logLevel = $xk, g = true) {
    super();
    this.g = g;
    this.setLevel(logLevel);
  }
  trace(message, ...args) {
    if (this.f(LogLevel.Trace)) {
      if (this.g) {
        console.log("%cTRACE", "color: #888", message, ...args);
      } else {
        console.log(message, ...args);
      }
    }
  }
  debug(message, ...args) {
    if (this.f(LogLevel.Debug)) {
      if (this.g) {
        console.log("%cDEBUG", "background: #eee; color: #888", message, ...args);
      } else {
        console.log(message, ...args);
      }
    }
  }
  info(message, ...args) {
    if (this.f(LogLevel.Info)) {
      if (this.g) {
        console.log("%c INFO", "color: #33f", message, ...args);
      } else {
        console.log(message, ...args);
      }
    }
  }
  warn(message, ...args) {
    if (this.f(LogLevel.Warning)) {
      if (this.g) {
        console.log("%c WARN", "color: #993", message, ...args);
      } else {
        console.log(message, ...args);
      }
    }
  }
  error(message, ...args) {
    if (this.f(LogLevel.Error)) {
      if (this.g) {
        console.log("%c  ERR", "color: #f33", message, ...args);
      } else {
        console.error(message, ...args);
      }
    }
  }
  flush() {
  }
};
var $Dk = class extends $zk {
  constructor(g, logLevel = $xk) {
    super();
    this.g = g;
    this.setLevel(logLevel);
  }
  trace(message, ...args) {
    if (this.f(LogLevel.Trace)) {
      this.g.log(LogLevel.Trace, [this.h(message), ...args]);
    }
  }
  debug(message, ...args) {
    if (this.f(LogLevel.Debug)) {
      this.g.log(LogLevel.Debug, [this.h(message), ...args]);
    }
  }
  info(message, ...args) {
    if (this.f(LogLevel.Info)) {
      this.g.log(LogLevel.Info, [this.h(message), ...args]);
    }
  }
  warn(message, ...args) {
    if (this.f(LogLevel.Warning)) {
      this.g.log(LogLevel.Warning, [this.h(message), ...args]);
    }
  }
  error(message, ...args) {
    if (this.f(LogLevel.Error)) {
      this.g.log(LogLevel.Error, [this.h(message), ...args]);
    }
  }
  h(msg) {
    if (typeof msg === "string") {
      return msg;
    }
    return $Kj(msg, this.f(LogLevel.Trace));
  }
  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 $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";
  }
}
var $Mk = new $ek("logLevel", $Jk(LogLevel.Info));

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

// out-build/vs/code/electron-utility/sharedProcess/contrib/codeCacheCleaner.js
var $9lc = class $9lc2 extends $0c {
  constructor(currentCodeCachePath, b, c) {
    super();
    this.b = b;
    this.c = c;
    this.a = this.b.quality !== "stable" ? 1e3 * 60 * 60 * 24 * 7 : 1e3 * 60 * 60 * 24 * 30 * 3;
    if (currentCodeCachePath) {
      const scheduler = this.B(new $_h(
        () => {
          this.f(currentCodeCachePath);
        },
        30 * 1e3
        /* after 30s */
      ));
      scheduler.schedule();
    }
  }
  async f(currentCodeCachePath) {
    this.c.trace("[code cache cleanup]: Starting to clean up old code cache folders.");
    try {
      const now = Date.now();
      const codeCacheRootPath = $yc(currentCodeCachePath);
      const currentCodeCache = $zc(currentCodeCachePath);
      const codeCaches = await Promises2.readdir(codeCacheRootPath);
      await Promise.all(codeCaches.map(async (codeCache) => {
        if (codeCache === currentCodeCache) {
          return;
        }
        const codeCacheEntryPath = $vc(codeCacheRootPath, codeCache);
        const codeCacheEntryStat = await fs2.promises.stat(codeCacheEntryPath);
        if (codeCacheEntryStat.isDirectory() && now - codeCacheEntryStat.mtime.getTime() > this.a) {
          this.c.trace(`[code cache cleanup]: Removing code cache folder ${codeCache}.`);
          return Promises2.rm(codeCacheEntryPath);
        }
      }));
    } catch (error) {
      $ab(error);
    }
  }
};
$9lc = __decorate([
  __param(1, $Nk),
  __param(2, $uk)
], $9lc);

// out-build/vs/code/electron-utility/sharedProcess/contrib/languagePackCachedDataCleaner.js
import * as fs3 from "fs";

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

// out-build/vs/code/electron-utility/sharedProcess/contrib/languagePackCachedDataCleaner.js
var $0lc = class $0lc2 extends $0c {
  constructor(b, c, f) {
    super();
    this.b = b;
    this.c = c;
    this.f = f;
    this.a = this.f.quality !== "stable" ? 1e3 * 60 * 60 * 24 * 7 : 1e3 * 60 * 60 * 24 * 30 * 3;
    if (this.b.isBuilt) {
      const scheduler = this.B(new $_h(
        () => {
          this.g();
        },
        40 * 1e3
        /* after 40s */
      ));
      scheduler.schedule();
    }
  }
  async g() {
    this.c.trace("[language pack cache cleanup]: Starting to clean up unused language packs.");
    try {
      const installed = /* @__PURE__ */ Object.create(null);
      const metaData = JSON.parse(await fs3.promises.readFile($vc(this.b.userDataPath, "languagepacks.json"), "utf8"));
      for (const locale of Object.keys(metaData)) {
        const entry = metaData[locale];
        installed[`${entry.hash}.${locale}`] = true;
      }
      const cacheDir = $vc(this.b.userDataPath, "clp");
      const cacheDirExists = await Promises2.exists(cacheDir);
      if (!cacheDirExists) {
        return;
      }
      const entries = await Promises2.readdir(cacheDir);
      for (const entry of entries) {
        if (installed[entry]) {
          this.c.trace(`[language pack cache cleanup]: Skipping folder ${entry}. Language pack still in use.`);
          continue;
        }
        this.c.trace(`[language pack cache cleanup]: Removing unused language pack: ${entry}`);
        await Promises2.rm($vc(cacheDir, entry));
      }
      const now = Date.now();
      for (const packEntry of Object.keys(installed)) {
        const folder = $vc(cacheDir, packEntry);
        const entries2 = await Promises2.readdir(folder);
        for (const entry of entries2) {
          if (entry === "tcf.json") {
            continue;
          }
          const candidate = $vc(folder, entry);
          const stat = await fs3.promises.stat(candidate);
          if (stat.isDirectory() && now - stat.mtime.getTime() > this.a) {
            this.c.trace(`[language pack cache cleanup]: Removing language pack cache folder: ${$vc(packEntry, entry)}`);
            await Promises2.rm(candidate);
          }
        }
      }
    } catch (error) {
      $ab(error);
    }
  }
};
$0lc = __decorate([
  __param(0, $8i),
  __param(1, $uk),
  __param(2, $Nk)
], $0lc);

// 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 $vp = "__web_extension";
var $wp = "skipWalkthrough";
var $xp = "extensionInstallSource";
var $yp = "dependecyOrPackExtensionInstall";
var $zp = "clientTargetPlatform";
var ExtensionInstallSource;
(function(ExtensionInstallSource2) {
  ExtensionInstallSource2["COMMAND"] = "command";
  ExtensionInstallSource2["SETTINGS_SYNC"] = "settingsSync";
})(ExtensionInstallSource || (ExtensionInstallSource = {}));
function $Ap(targetPlatform) {
  switch (targetPlatform) {
    case "win32-x64":
      return "Windows 64 bit";
    case "win32-arm64":
      return "Windows ARM";
    case "linux-x64":
      return "Linux 64 bit";
    case "linux-arm64":
      return "Linux ARM 64";
    case "linux-armhf":
      return "Linux ARM";
    case "alpine-x64":
      return "Alpine Linux 64 bit";
    case "alpine-arm64":
      return "Alpine ARM 64";
    case "darwin-x64":
      return "Mac";
    case "darwin-arm64":
      return "Mac Silicon";
    case "web":
      return "Web";
    case "universal":
      return "universal";
    case "unknown":
      return "unknown";
    case "undefined":
      return "undefined";
  }
}
function $Bp(targetPlatform) {
  switch (targetPlatform) {
    case "win32-x64":
      return "win32-x64";
    case "win32-arm64":
      return "win32-arm64";
    case "linux-x64":
      return "linux-x64";
    case "linux-arm64":
      return "linux-arm64";
    case "linux-armhf":
      return "linux-armhf";
    case "alpine-x64":
      return "alpine-x64";
    case "alpine-arm64":
      return "alpine-arm64";
    case "darwin-x64":
      return "darwin-x64";
    case "darwin-arm64":
      return "darwin-arm64";
    case "web":
      return "web";
    case "universal":
      return "universal";
    default:
      return "unknown";
  }
}
function $Cp(platform, arch2) {
  switch (platform) {
    case 3:
      if (arch2 === "x64") {
        return "win32-x64";
      }
      if (arch2 === "arm64") {
        return "win32-arm64";
      }
      return "unknown";
    case 2:
      if (arch2 === "x64") {
        return "linux-x64";
      }
      if (arch2 === "arm64") {
        return "linux-arm64";
      }
      if (arch2 === "arm") {
        return "linux-armhf";
      }
      return "unknown";
    case "alpine":
      if (arch2 === "x64") {
        return "alpine-x64";
      }
      if (arch2 === "arm64") {
        return "alpine-arm64";
      }
      return "unknown";
    case 1:
      if (arch2 === "x64") {
        return "darwin-x64";
      }
      if (arch2 === "arm64") {
        return "darwin-arm64";
      }
      return "unknown";
    case 0:
      return "web";
  }
}
function $Dp(allTargetPlatforms, productTargetPlatform) {
  return productTargetPlatform === "web" && !allTargetPlatforms.includes(
    "web"
    /* TargetPlatform.WEB */
  );
}
function $Ep(extensionTargetPlatform, allTargetPlatforms, productTargetPlatform) {
  if ($Dp(allTargetPlatforms, productTargetPlatform)) {
    return false;
  }
  if (extensionTargetPlatform === "undefined") {
    return true;
  }
  if (extensionTargetPlatform === "universal") {
    return true;
  }
  if (extensionTargetPlatform === "unknown") {
    return false;
  }
  if (extensionTargetPlatform === productTargetPlatform) {
    return true;
  }
  return false;
}
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 $Hp = class extends Error {
  constructor(message, code) {
    super(message);
    this.code = code;
    this.name = code;
  }
};
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 $Ip = class extends Error {
  constructor(message, code) {
    super(message);
    this.code = code;
    this.name = code;
  }
};
var $Jp = $Zi("extensionManagementService");
var $Kp = "extensionsIdentifiers/disabled";
var $Mp = $Zi("IGlobalExtensionEnablementService");
var $Np = $Zi("IExtensionTipsService");
var $Op = localize2(1790, "Extensions");
var $Pp = localize2(1791, "Preferences");

// out-build/vs/platform/languagePacks/common/languagePacks.js
function $us(extension) {
  return extension.tags.find((t) => t.startsWith("lp-"))?.split("lp-")[1];
}
var $vs = $Zi("languagePackService");
var $ws = class $ws2 extends $0c {
  constructor(c) {
    super();
    this.c = c;
  }
  async getAvailableLanguages() {
    const timeout = new $Pe();
    setTimeout(() => timeout.cancel(), 1e3);
    let result;
    try {
      result = await this.c.query({
        text: 'category:"language packs"',
        pageSize: 20
      }, timeout.token);
    } catch (_) {
      return [];
    }
    const languagePackExtensions = result.firstPage.filter((e) => e.properties.localizedLanguages?.length && e.tags.some((t) => t.startsWith("lp-")));
    const allFromMarketplace = languagePackExtensions.map((lp) => {
      const languageName = lp.properties.localizedLanguages?.[0];
      const locale = $us(lp);
      const baseQuickPick = this.f(locale, languageName, lp);
      return {
        ...baseQuickPick,
        extensionId: lp.identifier.id,
        galleryExtension: lp
      };
    });
    allFromMarketplace.push(this.f("en", "English"));
    return allFromMarketplace;
  }
  f(locale, languageName, languagePack) {
    const label = languageName ?? locale;
    let description;
    if (label !== locale) {
      description = `(${locale})`;
    }
    if (locale.toLowerCase() === $z.toLowerCase()) {
      description ??= "";
      description += localize(1942, null);
    }
    if (languagePack?.installCount) {
      description ??= "";
      const count = languagePack.installCount;
      let countLabel;
      if (count > 1e6) {
        countLabel = `${Math.floor(count / 1e5) / 10}M`;
      } else if (count > 1e3) {
        countLabel = `${Math.floor(count / 1e3)}K`;
      } else {
        countLabel = String(count);
      }
      description += ` $(cloud-download) ${countLabel}`;
    }
    return {
      id: locale,
      label,
      description
    };
  }
};
$ws = __decorate([
  __param(0, $Gp)
], $ws);

// out-build/vs/code/electron-utility/sharedProcess/contrib/localizationsUpdater.js
var $$lc = class $$lc2 extends $0c {
  constructor(a) {
    super();
    this.a = a;
    this.b();
  }
  b() {
    this.a.update();
  }
};
$$lc = __decorate([
  __param(0, $vs)
], $$lc);

// out-build/vs/code/electron-utility/sharedProcess/contrib/logsDataCleaner.js
var $_lc = class $_lc2 extends $0c {
  constructor(a, b) {
    super();
    this.a = a;
    this.b = b;
    const scheduler = this.B(new $_h(
      () => {
        this.c();
      },
      10 * 1e3
      /* after 10s */
    ));
    scheduler.schedule();
  }
  async c() {
    this.b.trace("[logs cleanup]: Starting to clean up old logs.");
    try {
      const currentLog = $xh(this.a.logsHome);
      const logsRoot = $zh(this.a.logsHome.with({ scheme: Schemas.file })).fsPath;
      const logFiles = await Promises2.readdir(logsRoot);
      const allSessions = logFiles.filter((logFile) => /^\d{8}T\d{6}$/.test(logFile));
      const oldSessions = allSessions.sort().filter((session) => session !== currentLog);
      const sessionsToDelete = oldSessions.slice(0, Math.max(0, oldSessions.length - 9));
      if (sessionsToDelete.length > 0) {
        this.b.trace(`[logs cleanup]: Removing log folders '${sessionsToDelete.join(", ")}'`);
        await Promise.all(sessionsToDelete.map((sessionToDelete) => Promises2.rm($vc(logsRoot, sessionToDelete))));
      }
    } catch (error) {
      $ab(error);
    }
  }
};
$_lc = __decorate([
  __param(0, $7i),
  __param(1, $uk)
], $_lc);

// out-build/vs/platform/storage/common/storageIpc.js
var BaseStorageDatabaseClient = class extends $0c {
  constructor(a, b, c) {
    super();
    this.a = a;
    this.b = b;
    this.c = c;
  }
  async getItems() {
    const serializableRequest = { profile: this.b, workspace: this.c };
    const items = await this.a.call("getItems", serializableRequest);
    return new Map(items);
  }
  updateItems(request2) {
    const serializableRequest = { profile: this.b, workspace: this.c };
    if (request2.insert) {
      serializableRequest.insert = Array.from(request2.insert.entries());
    }
    if (request2.delete) {
      serializableRequest.delete = Array.from(request2.delete.values());
    }
    return this.a.call("updateItems", serializableRequest);
  }
  optimize() {
    const serializableRequest = { profile: this.b, workspace: this.c };
    return this.a.call("optimize", serializableRequest);
  }
};
var BaseProfileAwareStorageDatabaseClient = class extends BaseStorageDatabaseClient {
  constructor(channel, profile) {
    super(channel, profile, void 0);
    this.f = this.B(new $De());
    this.onDidChangeItemsExternal = this.f.event;
    this.g();
  }
  g() {
    this.B(this.a.listen("onDidChangeStorage", { profile: this.b })((e) => this.h(e)));
  }
  h(e) {
    if (Array.isArray(e.changed) || Array.isArray(e.deleted)) {
      this.f.fire({
        changed: e.changed ? new Map(e.changed) : void 0,
        deleted: e.deleted ? new Set(e.deleted) : void 0
      });
    }
  }
};
var $cSb = class extends BaseProfileAwareStorageDatabaseClient {
  constructor(channel) {
    super(channel, void 0);
  }
  async close() {
    this.dispose();
  }
};
var $dSb = class extends BaseProfileAwareStorageDatabaseClient {
  constructor(channel, profile) {
    super(channel, profile);
  }
  async close() {
    this.dispose();
  }
};
var $eSb = class extends BaseStorageDatabaseClient {
  constructor(channel, workspace) {
    super(channel, void 0, workspace);
    this.onDidChangeItemsExternal = Event.None;
  }
  async close() {
    this.dispose();
  }
};
var $fSb = class {
  constructor(a) {
    this.a = a;
  }
  isUsed(path2) {
    const serializableRequest = { payload: path2, profile: void 0, workspace: void 0 };
    return this.a.call("isUsed", serializableRequest);
  }
};

// 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/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" };
function $cj(obj) {
  const workspaceIdentifier = obj;
  return typeof workspaceIdentifier?.id === "string" && URI.isUri(workspaceIdentifier.configPath);
}
var WorkbenchState;
(function(WorkbenchState2) {
  WorkbenchState2[WorkbenchState2["EMPTY"] = 1] = "EMPTY";
  WorkbenchState2[WorkbenchState2["FOLDER"] = 2] = "FOLDER";
  WorkbenchState2[WorkbenchState2["WORKSPACE"] = 3] = "WORKSPACE";
})(WorkbenchState || (WorkbenchState = {}));
var $jj = "code-workspace";
var $kj = `.${$jj}`;
var $lj = [{ name: localize(2503, null), extensions: [$jj] }];

// out-build/vs/platform/workspaces/node/workspaces.js
import { createHash } from "crypto";
var $Xjc = 128 / 4;

// out-build/vs/platform/native/common/native.js
var $ykc = $Zi("nativeHostService");

// out-build/vs/platform/ipc/common/mainProcessService.js
var $HOb = $Zi("mainProcessService");
var $IOb = class {
  constructor(a, b) {
    this.a = a;
    this.b = b;
  }
  getChannel(channelName) {
    return this.a.getChannel(channelName, this.b);
  }
  registerChannel(channelName, channel) {
    this.a.registerChannel(channelName, channel);
  }
};

// out-build/vs/code/electron-utility/sharedProcess/contrib/storageDataCleaner.js
var $amc = class $amc2 extends $0c {
  constructor(a, b, c, f) {
    super();
    this.a = a;
    this.b = b;
    this.c = c;
    this.f = f;
    const scheduler = this.B(new $_h(
      () => {
        this.g();
      },
      30 * 1e3
      /* after 30s */
    ));
    scheduler.schedule();
  }
  async g() {
    this.b.trace("[storage cleanup]: Starting to clean up workspace storage folders for unused empty workspaces.");
    try {
      const workspaceStorageHome = this.a.workspaceStorageHome.with({ scheme: Schemas.file }).fsPath;
      const workspaceStorageFolders = await Promises2.readdir(workspaceStorageHome);
      const storageClient = new $fSb(this.f.getChannel("storage"));
      await Promise.all(workspaceStorageFolders.map(async (workspaceStorageFolder) => {
        const workspaceStoragePath = $vc(workspaceStorageHome, workspaceStorageFolder);
        if (workspaceStorageFolder.length === $Xjc) {
          return;
        }
        if (workspaceStorageFolder === $_i.id) {
          return;
        }
        const windows = await this.c.getWindows({ includeAuxiliaryWindows: false });
        if (windows.some((window2) => window2.workspace?.id === workspaceStorageFolder)) {
          return;
        }
        const isStorageUsed = await storageClient.isUsed(workspaceStoragePath);
        if (isStorageUsed) {
          return;
        }
        this.b.trace(`[storage cleanup]: Deleting workspace storage folder ${workspaceStorageFolder} as it seems to be an unused empty workspace.`);
        await Promises2.rm(workspaceStoragePath);
      }));
    } catch (error) {
      $ab(error);
    }
  }
};
$amc = __decorate([
  __param(0, $8i),
  __param(1, $uk),
  __param(2, $ykc),
  __param(3, $HOb)
], $amc);

// out-build/vs/platform/checksum/common/checksumService.js
var $bmc = $Zi("checksumService");

// out-build/vs/platform/checksum/node/checksumService.js
import { createHash as createHash2 } from "crypto";

// 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, code) {
    const providerError = new _$Gl(error.toString(), code);
    $Jl(providerError, code);
    return providerError;
  }
  constructor(message, code) {
    super(message);
    this.code = code;
  }
};
function $Hl(error, code) {
  return $Gl.create(error, code);
}
function $Il(error) {
  if (!error) {
    return $Hl(localize(1879, null), FileSystemProviderErrorCode.Unknown);
  }
  return error;
}
function $Jl(error, code) {
  error.name = code ? `${code} (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(path2, candidate, ignoreCase) {
  if (!path2 || !candidate || path2 === candidate) {
    return false;
  }
  if (candidate.length > path2.length) {
    return false;
  }
  if (candidate.charAt(candidate.length - 1) !== sep) {
    candidate += sep;
  }
  if (ignoreCase) {
    return $1f(path2, candidate);
  }
  return path2.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 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/checksum/node/checksumService.js
var $cmc = class $cmc2 {
  constructor(a) {
    this.a = a;
  }
  async checksum(resource) {
    const stream = (await this.a.readFileStream(resource)).value;
    return new Promise((resolve, reject) => {
      const hash = createHash2("sha256");
      $Ye(stream, {
        onData: (data) => hash.update(data.buffer),
        onError: (error) => reject(error),
        onEnd: () => resolve(hash.digest("base64").replace(/=+$/, ""))
      });
    });
  }
};
$cmc = __decorate([
  __param(0, $ul)
], $cmc);

// 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, path3) {
    let current = config2;
    for (const component of path3) {
      if (typeof current !== "object" || current === null) {
        return void 0;
      }
      current = current[component];
    }
    return current;
  }
  const path2 = settingPath.split(".");
  const result = accessSetting(config, path2);
  return typeof result === "undefined" ? defaultValue : result;
}
function $Dj(settingKey) {
  return settingKey.replace(/[\[\]]/g, "");
}

// 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 code = text.charCodeAt(pos);
    if (isWhitespace(code)) {
      do {
        pos++;
        value += String.fromCharCode(code);
        code = text.charCodeAt(pos);
      } while (isWhitespace(code));
      return token = 15;
    }
    if (isLineBreak(code)) {
      pos++;
      value += String.fromCharCode(code);
      if (code === 13 && text.charCodeAt(pos) === 10) {
        pos++;
        value += "\n";
      }
      return token = 14;
    }
    switch (code) {
      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(code);
        pos++;
        return token = 16;
      }
      case 45:
        value += String.fromCharCode(code);
        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(code)) {
          pos++;
          code = 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(code);
        pos++;
        return token = 16;
    }
  }
  function isUnknownContentCharacter(code) {
    if (isWhitespace(code) || isLineBreak(code)) {
      return false;
    }
    switch (code) {
      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, path2) {
  if (!root) {
    return void 0;
  }
  let node = root;
  for (const segment of path2) {
    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/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 $ro(obj, options) {
  const content = JSON.stringify(obj, void 0, options.insertSpaces ? options.tabSize || 4 : "	");
  if (options.eol !== void 0) {
    return content.replace(/\r\n|\r|\n/g, options.eol);
  }
  return content;
}
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 path2 = originalPath.slice();
  const errors = [];
  const root = $io(text, errors);
  let parent = void 0;
  let lastSegment = void 0;
  while (path2.length > 0) {
    lastSegment = path2.pop();
    parent = $jo(root, path2);
    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 edit2;
      if (index > 0) {
        const previous = parent.children[index - 1];
        edit2 = { offset: previous.offset + previous.length, length: 0, content: "," + newProperty };
      } else if (parent.children.length === 0) {
        edit2 = { offset: parent.offset + 1, length: 0, content: newProperty };
      } else {
        edit2 = { offset: parent.offset + 1, length: 0, content: newProperty + "," };
      }
      return $wo(text, edit2, formattingOptions);
    }
  } else if (parent.type === "array" && typeof lastSegment === "number" && Array.isArray(parent.children)) {
    if (value !== void 0) {
      const newProperty = `${JSON.stringify(value)}`;
      let edit2;
      if (parent.children.length === 0 || lastSegment === 0) {
        edit2 = { 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];
        edit2 = { offset: previous.offset + previous.length, length: 0, content: "," + newProperty };
      }
      return $wo(text, edit2, formattingOptions);
    } else {
      const removalIndex = lastSegment;
      const toRemove = parent.children[removalIndex];
      let edit2;
      if (parent.children.length === 1) {
        edit2 = { 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;
        edit2 = { offset, length: parentEndOffset - 2 - offset, content: "" };
      } else {
        edit2 = { offset: toRemove.offset, length: parent.children[removalIndex + 1].offset - toRemove.offset, content: "" };
      }
      return $wo(text, edit2, formattingOptions);
    }
  } else {
    throw new Error(`Can not add ${typeof lastSegment !== "number" ? "index" : "property"} to parent of type ${parent.type}`);
  }
}
function $wo(text, edit2, formattingOptions) {
  let newText = $xo(text, edit2);
  let begin = edit2.offset;
  let end = edit2.offset + edit2.content.length;
  if (edit2.length === 0 || edit2.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, edit2) {
  return text.substring(0, edit2.offset) + edit2.content + text.substring(edit2.offset + edit2.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/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 $Eo(obj) {
  const seen = /* @__PURE__ */ new Set();
  return JSON.stringify(obj, (key, value) => {
    if ($Ag(value) || Array.isArray(value)) {
      if (seen.has(value)) {
        return "[Circular]";
      } else {
        seen.add(value);
      }
    }
    if (typeof value === "bigint") {
      return `[BigInt ${value.toString()}]`;
    }
    return value;
  });
}

// 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(type2) {
  const t = Array.isArray(type2) ? type2[0] : type2;
  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;
}
function $8o(configurationNode) {
  const result = {};
  for (const configuration of configurationNode) {
    const properties = configuration.properties;
    if ($Ag(properties)) {
      for (const key in properties) {
        result[key] = properties[key];
      }
    }
    if (configuration.allOf) {
      Object.assign(result, $8o(configuration.allOf));
    }
  }
  return result;
}
function $9o(scope) {
  switch (scope) {
    case "application":
      return 1;
    case "machine":
      return 2;
    case "resource":
      return 4;
    case "machine-overridable":
      return 6;
    case "language-overridable":
      return 5;
    default:
      return 3;
  }
}

// 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 } = compare(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 } = compare(this.l, policyConfiguration);
    const keys = [...added, ...updated, ...removed];
    if (keys.length) {
      this.updatePolicyConfiguration(policyConfiguration);
    }
    return { keys, overrides: [] };
  }
  compareAndUpdateApplicationConfiguration(application) {
    const { added, updated, removed, overrides } = compare(this.applicationConfiguration, application);
    const keys = [...added, ...updated, ...removed];
    if (keys.length) {
      this.updateApplicationConfiguration(application);
    }
    return { keys, overrides };
  }
  compareAndUpdateLocalUserConfiguration(user) {
    const { added, updated, removed, overrides } = compare(this.localUserConfiguration, user);
    const keys = [...added, ...updated, ...removed];
    if (keys.length) {
      this.updateLocalUserConfiguration(user);
    }
    return { keys, overrides };
  }
  compareAndUpdateRemoteUserConfiguration(user) {
    const { added, updated, removed, overrides } = compare(this.remoteUserConfiguration, user);
    const keys = [...added, ...updated, ...removed];
    if (keys.length) {
      this.updateRemoteUserConfiguration(user);
    }
    return { keys, overrides };
  }
  compareAndUpdateWorkspaceConfiguration(workspaceConfiguration) {
    const { added, updated, removed, overrides } = compare(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 } = compare(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 } = compare(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 code = this.d.charCodeAt(pos);
    if (code !== this.b && code !== 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 compare(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/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/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 path2 = overrides?.overrideIdentifiers?.length ? [$4o(overrides.overrideIdentifiers), key] : [key];
    await this.j.write(path2, 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(path2, value) {
    return this.a.queue(() => this.e(path2, value));
  }
  async e(path2, 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, path2, value);
    content = $yo(content, edits);
    await this.c.writeFile(this.b, $7e.fromString(content));
  }
  f(content, path2, value) {
    const { tabSize, insertSpaces, eol } = this.h;
    if (!path2.length) {
      const content2 = JSON.stringify(value, null, insertSpaces ? " ".repeat(tabSize) : "	");
      return [{
        content: content2,
        length: content2.length,
        offset: 0
      }];
    }
    return $vo(content, path2, 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/common/diagnostics.js
var ID = "diagnosticsService";
var $bn = $Zi(ID);
function $cn(x) {
  return !!x.hostName && !!x.errorMessage;
}

// out-build/vs/platform/diagnostics/node/diagnosticsService.js
import * as fs4 from "fs";
import * as osLib from "os";

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

// 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/node/macAddress.js
import { networkInterfaces } from "os";

// 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;
  }
}();

// out-build/vs/base/node/ps.js
import { exec } from "child_process";
function $ht(rootPid) {
  return new Promise((resolve, 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);
                }
              });
              resolve(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(" ");
        exec(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;
            }
            resolve(rootItem);
          }
        });
      };
      var calculateLinuxCpuUsage = calculateLinuxCpuUsage2;
      exec("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);
            exec(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=";
          exec(`${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 {
                  resolve(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/telemetry/common/telemetry.js
var $tm = $Zi("telemetryService");
var $um = $Zi("customEndpointTelemetryService");
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/diagnostics/node/diagnosticsService.js
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 (resolve) => {
      let files;
      token.readdirCount++;
      try {
        files = await Promises2.readdir(dir, { withFileTypes: true });
      } catch (error) {
        resolve();
        return;
      }
      if (token.count >= MAX_FILES) {
        token.count += files.length;
        token.maxReached = true;
        resolve();
        return;
      }
      let pending = files.length;
      if (pending === 0) {
        resolve();
        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) {
            resolve();
            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) {
            resolve();
            return;
          }
        }
      }
    });
  }
  const statsPromise = Promises.withAsyncBody(async (resolve) => {
    const token = { count: 0, maxReached: false, readdirCount: 0 };
    const sw = new $xe(true);
    await collect(folder, folder, filter, token);
    const launchConfigs = await $kt(folder);
    resolve({
      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 cpus2 = osLib.cpus();
  if (cpus2 && cpus2.length > 0) {
    machineInfo.cpus = `${cpus2[0].model} (${cpus2.length} x ${cpus2[0].speed})`;
  }
  return machineInfo;
}
async function $kt(folder) {
  try {
    const launchConfigs = /* @__PURE__ */ new Map();
    const launchConfig = $vc(folder, ".vscode", "launch.json");
    const contents = await fs4.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 type2 = each["type"];
        if (type2) {
          if (launchConfigs.has(type2)) {
            launchConfigs.set(type2, launchConfigs.get(type2) + 1);
          } else {
            launchConfigs.set(type2, 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 cpus2 = osLib.cpus();
    if (cpus2 && cpus2.length > 0) {
      output.push(`CPUs:             ${cpus2[0].model} (${cpus2.length} x ${cpus2[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: os4, cpus: cpus2 } = $jt();
    const systemInfo = {
      os: os4,
      memory,
      cpus: cpus2,
      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/download/common/download.js
var $kp = $Zi("downloadService");

// 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, request2) {
    const prefix = `[network] #${++this.a}: ${options.url}`;
    this.b.trace(`${prefix} - begin`, options.type, new LoggableHeaders(options.headers ?? {}));
    try {
      const result = await request2();
      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 $uq(context) {
  if ($tq(context)) {
    return null;
  }
  const buffer = await $gf(context.stream);
  return buffer.toString();
}
async function $vq(context) {
  if (!$sq(context)) {
    throw new Error("Server returned " + context.res.statusCode);
  }
  return $uq(context);
}
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 configurationRegistry2 = $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
      }
    }
  };
  configurationRegistry2.updateConfigurations({ add: [proxyConfiguration], remove: oldProxyConfiguration ? [oldProxyConfiguration] : [] });
}
registerProxyConfigurations(
  1
  /* ConfigurationScope.APPLICATION */
);

// out-build/vs/platform/download/common/downloadService.js
var $1S = class $1S2 {
  constructor(a, b) {
    this.a = a;
    this.b = b;
  }
  async download(resource, target, cancellationToken = CancellationToken.None) {
    if (resource.scheme === Schemas.file || resource.scheme === Schemas.vscodeRemote) {
      await this.b.copy(resource, target);
      return;
    }
    const options = { type: "GET", url: resource.toString(true) };
    const context = await this.a.request(options, cancellationToken);
    if (context.res.statusCode === 200) {
      await this.b.writeFile(target, context.stream);
    } else {
      const message = await $vq(context);
      throw new Error(`Expected 200, got back ${context.res.statusCode} instead.

${message}`);
    }
  }
};
$1S = __decorate([
  __param(0, $qq),
  __param(1, $ul)
], $1S);

// 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 $Pn(manifest) {
  return $Qn(manifest);
}
function $Qn(manifest) {
  return manifest.contributes && manifest.contributes.localizations ? manifest.contributes.localizations.length > 0 : false;
}
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/telemetry/common/commonProperties.js
function getPlatformDetail(hostname3) {
  if ($x === 2 && /^penguin(\.|$)/i.test(hostname3)) {
    return "chromebook";
  }
  return void 0;
}
function $Qp(release4, hostname3, arch2, commit, version, machineId, sqmId, devDeviceId, isInternalTelemetry, product2) {
  const result = /* @__PURE__ */ Object.create(null);
  result["common.machineId"] = machineId;
  result["common.sqmId"] = sqmId;
  result["common.devDeviceId"] = devDeviceId;
  result["sessionID"] = $jh() + Date.now();
  result["commitHash"] = commit;
  result["version"] = version;
  result["common.platformVersion"] = (release4 || "").replace(/^(\d+)(\.\d+)?(\.\d+)?(.*)/, "$1$2$3");
  result["common.platform"] = $k($x);
  result["common.nodePlatform"] = $pc;
  result["common.nodeArch"] = arch2;
  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();
var $Wp = "telemetry";
var $Yp = { log: () => null, flush: () => Promise.resolve(void 0) };
function $Zp(productService, environmentService) {
  if (!environmentService.isBuilt && !environmentService.disableTelemetry) {
    return true;
  }
  return !(environmentService.disableTelemetry || !productService.enableTelemetry);
}
function $1p(productService, environmentService) {
  if (environmentService.extensionTestsLocationURI) {
    return true;
  }
  if (environmentService.isBuilt) {
    return false;
  }
  if (environmentService.disableTelemetry) {
    return false;
  }
  if (productService.enableTelemetry && productService.aiConfig?.ariaKey) {
    return false;
  }
  return true;
}
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 $3p(data) {
  const properties = {};
  const measurements = {};
  const flat = {};
  flatten(data, flat);
  for (let prop in flat) {
    prop = prop.length > 150 ? prop.substr(prop.length - 149) : prop;
    const value = flat[prop];
    if (typeof value === "number") {
      measurements[prop] = value;
    } else if (typeof value === "boolean") {
      measurements[prop] = value ? 1 : 0;
    } else if (typeof value === "string") {
      if (value.length > 8192) {
        console.warn(`Telemetry property: ${prop} has been trimmed to 8192, the original length is ${value.length}`);
      }
      properties[prop] = value.substring(0, 8191);
    } else if (typeof value !== "undefined" && value !== null) {
      properties[prop] = value;
    }
  }
  return {
    properties,
    measurements
  };
}
function flatten(obj, result, order = 0, prefix) {
  if (!obj) {
    return;
  }
  for (const item of Object.getOwnPropertyNames(obj)) {
    const value = obj[item];
    const index = prefix ? prefix + item : item;
    if (Array.isArray(value)) {
      result[index] = $Eo(value);
    } else if (value instanceof Date) {
      result[index] = value.toISOString();
    } else if ($Ag(value)) {
      if (order < 2) {
        flatten(value, result, order + 1, index + ".");
      } else {
        result[index] = $Eo(value);
      }
    } else {
      result[index] = value;
    }
  }
}
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/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;
  }
};
var EXTENSION_IDENTIFIER_WITH_VERSION_REGEX = /^([^.]+\..+)@((prerelease)|(\d+\.\d+\.\d+(-.*)?))$/;
function $0p(id2) {
  const matches = EXTENSION_IDENTIFIER_WITH_VERSION_REGEX.exec(id2);
  if (matches && matches[1]) {
    return [$_p(matches[1]), matches[2]];
  }
  return [$_p(id2), void 0];
}
function $$p(publisher, name) {
  return `${publisher}.${name}`;
}
function $_p(id2) {
  return id2.toLowerCase();
}
function $aq(publisher, name) {
  return $_p($$p(publisher ?? $In, name));
}
function $bq(extensions, getExtensionIdentifier) {
  const byExtension = [];
  const findGroup = (extension) => {
    for (const group of byExtension) {
      if (group.some((e) => $8p(getExtensionIdentifier(e), getExtensionIdentifier(extension)))) {
        return group;
      }
    }
    return null;
  };
  for (const extension of extensions) {
    const group = findGroup(extension);
    if (group) {
      group.push(extension);
    } else {
      byExtension.push([extension]);
    }
  }
  return byExtension;
}
function $cq(extension) {
  return {
    id: extension.identifier.id,
    name: extension.manifest.name,
    galleryId: null,
    publisherId: extension.publisherId,
    publisherName: extension.manifest.publisher,
    publisherDisplayName: extension.publisherDisplayName,
    dependencies: extension.manifest.extensionDependencies && extension.manifest.extensionDependencies.length > 0
  };
}
function $dq(extension) {
  return {
    id: new $Sp(extension.identifier.id),
    name: new $Sp(extension.name),
    version: extension.version,
    galleryId: extension.identifier.uuid,
    publisherId: extension.publisherId,
    publisherName: extension.publisher,
    publisherDisplayName: extension.publisherDisplayName,
    isPreReleaseVersion: extension.properties.isPreReleaseVersion,
    dependencies: !!(extension.properties.dependencies && extension.properties.dependencies.length > 0),
    isSigned: extension.isSigned,
    ...extension.telemetryData
  };
}
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/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/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((resolve) => this.n.push(resolve));
  }
  isInMemory() {
    return this.s.hint === StorageHint.STORAGE_IN_MEMORY;
  }
};

// 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 $8l(profile, scheme) {
  return {
    id: profile.id,
    isDefault: profile.isDefault,
    name: profile.name,
    shortName: profile.shortName,
    icon: profile.icon,
    location: URI.revive(profile.location).with({ scheme }),
    globalStorageHome: URI.revive(profile.globalStorageHome).with({ scheme }),
    settingsResource: URI.revive(profile.settingsResource).with({ scheme }),
    keybindingsResource: URI.revive(profile.keybindingsResource).with({ scheme }),
    tasksResource: URI.revive(profile.tasksResource).with({ scheme }),
    snippetsHome: URI.revive(profile.snippetsHome).with({ scheme }),
    extensionsResource: URI.revive(profile.extensionsResource).with({ scheme }),
    cacheHome: URI.revive(profile.cacheHome).with({ scheme }),
    useDefaultFlags: profile.useDefaultFlags,
    isTransient: profile.isTransient,
    workspaces: profile.workspaces?.map((w) => URI.revive(w))
  };
}
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/extensionManagement/common/extensionEnablementService.js
var $ERb = class $ERb2 extends $0c {
  constructor(storageService, extensionManagementService) {
    super();
    this.a = new $De();
    this.onDidChangeEnablement = this.a.event;
    this.b = this.B(new $FRb(storageService));
    this.B(this.b.onDidChange((extensions) => this.a.fire({ extensions, source: "storage" })));
    this.B(extensionManagementService.onDidInstallExtensions((e) => e.forEach(({ local, operation }) => {
      if (local && operation === 4) {
        this.f(local.identifier);
      }
    })));
  }
  async enableExtension(extension, source) {
    if (this.f(extension)) {
      this.a.fire({ extensions: [extension], source });
      return true;
    }
    return false;
  }
  async disableExtension(extension, source) {
    if (this.c(extension)) {
      this.a.fire({ extensions: [extension], source });
      return true;
    }
    return false;
  }
  getDisabledExtensions() {
    return this.h($Kp);
  }
  async getDisabledExtensionsAsync() {
    return this.getDisabledExtensions();
  }
  c(identifier) {
    const disabledExtensions = this.getDisabledExtensions();
    if (disabledExtensions.every((e) => !$8p(e, identifier))) {
      disabledExtensions.push(identifier);
      this.g(disabledExtensions);
      return true;
    }
    return false;
  }
  f(identifier) {
    const disabledExtensions = this.getDisabledExtensions();
    for (let index = 0; index < disabledExtensions.length; index++) {
      const disabledExtension = disabledExtensions[index];
      if ($8p(disabledExtension, identifier)) {
        disabledExtensions.splice(index, 1);
        this.g(disabledExtensions);
        return true;
      }
    }
    return false;
  }
  g(disabledExtensions) {
    this.j($Kp, disabledExtensions);
  }
  h(storageId) {
    return this.b.get(
      storageId,
      0
      /* StorageScope.PROFILE */
    );
  }
  j(storageId, extensions) {
    this.b.set(
      storageId,
      extensions,
      0
      /* StorageScope.PROFILE */
    );
  }
};
$ERb = __decorate([
  __param(0, $Dq),
  __param(1, $Jp)
], $ERb);
var $FRb = class extends $0c {
  constructor(c) {
    super();
    this.c = c;
    this.a = /* @__PURE__ */ Object.create(null);
    this.b = this.B(new $De());
    this.onDidChange = this.b.event;
    this.B(c.onDidChangeValue(0, void 0, this.B(new $9c()))((e) => this.f(e)));
  }
  get(key, scope) {
    let value;
    if (scope === 0) {
      if ($Hg(this.a[key])) {
        this.a[key] = this.g(key, scope);
      }
      value = this.a[key];
    } else {
      value = this.g(key, scope);
    }
    return JSON.parse(value);
  }
  set(key, value, scope) {
    const newValue = JSON.stringify(value.map(({ id: id2, uuid }) => ({ id: id2, uuid })));
    const oldValue = this.g(key, scope);
    if (oldValue !== newValue) {
      if (scope === 0) {
        if (value.length) {
          this.a[key] = newValue;
        } else {
          delete this.a[key];
        }
      }
      this.h(key, value.length ? newValue : void 0, scope);
    }
  }
  f(storageChangeEvent) {
    if (!$Hg(this.a[storageChangeEvent.key])) {
      const newValue = this.g(storageChangeEvent.key, storageChangeEvent.scope);
      if (newValue !== this.a[storageChangeEvent.key]) {
        const oldValues = this.get(storageChangeEvent.key, storageChangeEvent.scope);
        delete this.a[storageChangeEvent.key];
        const newValues = this.get(storageChangeEvent.key, storageChangeEvent.scope);
        const added = oldValues.filter((oldValue) => !newValues.some((newValue2) => $8p(oldValue, newValue2)));
        const removed = newValues.filter((newValue2) => !oldValues.some((oldValue) => $8p(oldValue, newValue2)));
        if (added.length || removed.length) {
          this.b.fire([...added, ...removed]);
        }
      }
    }
  }
  g(key, scope) {
    return this.c.get(key, scope, "[]");
  }
  h(key, value, scope) {
    if (value) {
      this.c.store(
        key,
        value,
        scope,
        1
        /* StorageTarget.MACHINE */
      );
    } else {
      this.c.remove(key, scope);
    }
  }
};

// out-build/vs/base/parts/request/common/request.js
var offlineName = "Offline";
function $rp(error) {
  if (error instanceof $sp) {
    return true;
  }
  return error instanceof Error && error.name === offlineName && error.message === offlineName;
}
var $sp = class extends Error {
  constructor() {
    super(offlineName);
    this.name = this.message;
  }
};

// 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/semver/semver.js
var exports = {};
var module2 = { exports };
!function(e, r) {
  if ("object" == typeof exports && "object" == typeof module2) module2.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 = module2.exports.SEMVER_SPEC_VERSION;
var parse = module2.exports.parse;
var valid = module2.exports.valid;
var coerce = module2.exports.coerce;
var clean = module2.exports.clean;
var inc = module2.exports.inc;
var major = module2.exports.major;
var minor = module2.exports.minor;
var patch = module2.exports.patch;
var prerelease = module2.exports.prerelease;
var gt = module2.exports.gt;
var gte = module2.exports.gte;
var lt = module2.exports.lt;
var lte = module2.exports.lte;
var eq = module2.exports.eq;
var neq = module2.exports.neq;
var cmp3 = module2.exports.cmp;
var compare2 = module2.exports.compare;
var rcompare = module2.exports.rcompare;
var compareIdentifiers = module2.exports.compareIdentifiers;
var rcompareIdentifiers = module2.exports.rcompareIdentifiers;
var compareBuild = module2.exports.compareBuild;
var sort = module2.exports.sort;
var rsort = module2.exports.rsort;
var diff = module2.exports.diff;
var validRange = module2.exports.validRange;
var satisfies = module2.exports.satisfies;
var maxSatisfying = module2.exports.maxSatisfying;
var minSatisfying = module2.exports.minSatisfying;
var minVersion = module2.exports.minVersion;
var gtr = module2.exports.gtr;
var ltr = module2.exports.ltr;
var outside = module2.exports.outside;
var intersects = module2.exports.intersects;
var SemVer = module2.exports.SemVer;
var Comparator = module2.exports.Comparator;
var Range = module2.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 $oq(engine, version, date) {
  return engine === "*" || isVersionValid(version, date, engine);
}
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/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/platform/extensionManagement/common/extensionGalleryService.js
var CURRENT_TARGET_PLATFORM = $r ? "web" : $Cp($x, $qc);
var ACTIVITY_HEADER_NAME = "X-Market-Search-Activity-Id";
var Flags;
(function(Flags2) {
  Flags2[Flags2["None"] = 0] = "None";
  Flags2[Flags2["IncludeVersions"] = 1] = "IncludeVersions";
  Flags2[Flags2["IncludeFiles"] = 2] = "IncludeFiles";
  Flags2[Flags2["IncludeCategoryAndTags"] = 4] = "IncludeCategoryAndTags";
  Flags2[Flags2["IncludeSharedAccounts"] = 8] = "IncludeSharedAccounts";
  Flags2[Flags2["IncludeVersionProperties"] = 16] = "IncludeVersionProperties";
  Flags2[Flags2["ExcludeNonValidated"] = 32] = "ExcludeNonValidated";
  Flags2[Flags2["IncludeInstallationTargets"] = 64] = "IncludeInstallationTargets";
  Flags2[Flags2["IncludeAssetUri"] = 128] = "IncludeAssetUri";
  Flags2[Flags2["IncludeStatistics"] = 256] = "IncludeStatistics";
  Flags2[Flags2["IncludeLatestVersionOnly"] = 512] = "IncludeLatestVersionOnly";
  Flags2[Flags2["Unpublished"] = 4096] = "Unpublished";
  Flags2[Flags2["IncludeNameConflictInfo"] = 32768] = "IncludeNameConflictInfo";
})(Flags || (Flags = {}));
function flagsToString(...flags) {
  return String(flags.reduce((r, f) => r | f, 0));
}
var FilterType;
(function(FilterType2) {
  FilterType2[FilterType2["Tag"] = 1] = "Tag";
  FilterType2[FilterType2["ExtensionId"] = 4] = "ExtensionId";
  FilterType2[FilterType2["Category"] = 5] = "Category";
  FilterType2[FilterType2["ExtensionName"] = 7] = "ExtensionName";
  FilterType2[FilterType2["Target"] = 8] = "Target";
  FilterType2[FilterType2["Featured"] = 9] = "Featured";
  FilterType2[FilterType2["SearchText"] = 10] = "SearchText";
  FilterType2[FilterType2["ExcludeWithFlags"] = 12] = "ExcludeWithFlags";
})(FilterType || (FilterType = {}));
var AssetType = {
  Icon: "Microsoft.VisualStudio.Services.Icons.Default",
  Details: "Microsoft.VisualStudio.Services.Content.Details",
  Changelog: "Microsoft.VisualStudio.Services.Content.Changelog",
  Manifest: "Microsoft.VisualStudio.Code.Manifest",
  VSIX: "Microsoft.VisualStudio.Services.VSIXPackage",
  License: "Microsoft.VisualStudio.Services.Content.License",
  Repository: "Microsoft.VisualStudio.Services.Links.Source",
  Signature: "Microsoft.VisualStudio.Services.VsixSignature"
};
var PropertyType = {
  Dependency: "Microsoft.VisualStudio.Code.ExtensionDependencies",
  ExtensionPack: "Microsoft.VisualStudio.Code.ExtensionPack",
  Engine: "Microsoft.VisualStudio.Code.Engine",
  PreRelease: "Microsoft.VisualStudio.Code.PreRelease",
  EnabledApiProposals: "Microsoft.VisualStudio.Code.EnabledApiProposals",
  LocalizedLanguages: "Microsoft.VisualStudio.Code.LocalizedLanguages",
  WebExtension: "Microsoft.VisualStudio.Code.WebExtension",
  SponsorLink: "Microsoft.VisualStudio.Code.SponsorLink",
  SupportLink: "Microsoft.VisualStudio.Services.Links.Support",
  ExecutesCode: "Microsoft.VisualStudio.Code.ExecutesCode"
};
var DefaultPageSize = 10;
var DefaultQueryState = {
  pageNumber: 1,
  pageSize: DefaultPageSize,
  sortBy: 0,
  sortOrder: 0,
  flags: Flags.None,
  criteria: [],
  assetTypes: []
};
var Query = class _Query {
  constructor(d = DefaultQueryState) {
    this.d = d;
  }
  get pageNumber() {
    return this.d.pageNumber;
  }
  get pageSize() {
    return this.d.pageSize;
  }
  get sortBy() {
    return this.d.sortBy;
  }
  get sortOrder() {
    return this.d.sortOrder;
  }
  get flags() {
    return this.d.flags;
  }
  get criteria() {
    return this.d.criteria;
  }
  withPage(pageNumber, pageSize = this.d.pageSize) {
    return new _Query({ ...this.d, pageNumber, pageSize });
  }
  withFilter(filterType, ...values) {
    const criteria = [
      ...this.d.criteria,
      ...values.length ? values.map((value) => ({ filterType, value })) : [{ filterType }]
    ];
    return new _Query({ ...this.d, criteria });
  }
  withSortBy(sortBy) {
    return new _Query({ ...this.d, sortBy });
  }
  withSortOrder(sortOrder) {
    return new _Query({ ...this.d, sortOrder });
  }
  withFlags(...flags) {
    return new _Query({ ...this.d, flags: flags.reduce((r, f) => r | f, 0) });
  }
  withAssetTypes(...assetTypes) {
    return new _Query({ ...this.d, assetTypes });
  }
  withSource(source) {
    return new _Query({ ...this.d, source });
  }
  get raw() {
    const { criteria, pageNumber, pageSize, sortBy, sortOrder, flags, assetTypes } = this.d;
    const filters = [{ criteria, pageNumber, pageSize, sortBy, sortOrder }];
    return { filters, assetTypes, flags };
  }
  get searchText() {
    const criterium = this.d.criteria.filter((criterium2) => criterium2.filterType === FilterType.SearchText)[0];
    return criterium && criterium.value ? criterium.value : "";
  }
  get telemetryData() {
    return {
      filterTypes: this.d.criteria.map((criterium) => String(criterium.filterType)),
      flags: this.d.flags,
      sortBy: String(this.sortBy),
      sortOrder: String(this.sortOrder),
      pageNumber: String(this.pageNumber),
      source: this.d.source,
      searchTextLength: this.searchText.length
    };
  }
};
function getStatistic(statistics, name) {
  const result = (statistics || []).filter((s) => s.statisticName === name)[0];
  return result ? result.value : 0;
}
function getCoreTranslationAssets(version) {
  const coreTranslationAssetPrefix = "Microsoft.VisualStudio.Code.Translation.";
  const result = version.files.filter((f) => f.assetType.indexOf(coreTranslationAssetPrefix) === 0);
  return result.reduce((result2, file) => {
    const asset = getVersionAsset(version, file.assetType);
    if (asset) {
      result2.push([file.assetType.substring(coreTranslationAssetPrefix.length), asset]);
    }
    return result2;
  }, []);
}
function getRepositoryAsset(version) {
  if (version.properties) {
    const results = version.properties.filter((p) => p.key === AssetType.Repository);
    const gitRegExp = new RegExp("((git|ssh|http(s)?)|(git@[\\w.]+))(:(//)?)([\\w.@:/\\-~]+)(.git)(/)?");
    const uri = results.filter((r) => gitRegExp.test(r.value))[0];
    return uri ? { uri: uri.value, fallbackUri: uri.value } : null;
  }
  return getVersionAsset(version, AssetType.Repository);
}
function getDownloadAsset(version) {
  return {
    // always use fallbackAssetUri for download asset to hit the Marketplace API so that downloads are counted
    uri: `${version.fallbackAssetUri}/${AssetType.VSIX}?redirect=true${version.targetPlatform ? `&targetPlatform=${version.targetPlatform}` : ""}`,
    fallbackUri: `${version.fallbackAssetUri}/${AssetType.VSIX}${version.targetPlatform ? `?targetPlatform=${version.targetPlatform}` : ""}`
  };
}
function getVersionAsset(version, type2) {
  const result = version.files.filter((f) => f.assetType === type2)[0];
  return result ? {
    uri: `${version.assetUri}/${type2}${version.targetPlatform ? `?targetPlatform=${version.targetPlatform}` : ""}`,
    fallbackUri: `${version.fallbackAssetUri}/${type2}${version.targetPlatform ? `?targetPlatform=${version.targetPlatform}` : ""}`
  } : null;
}
function getExtensions(version, property) {
  const values = version.properties ? version.properties.filter((p) => p.key === property) : [];
  const value = values.length > 0 && values[0].value;
  return value ? value.split(",").map((v) => $_p(v)) : [];
}
function getEngine(version) {
  const values = version.properties ? version.properties.filter((p) => p.key === PropertyType.Engine) : [];
  return values.length > 0 && values[0].value || "";
}
function isPreReleaseVersion(version) {
  const values = version.properties ? version.properties.filter((p) => p.key === PropertyType.PreRelease) : [];
  return values.length > 0 && values[0].value === "true";
}
function executesCode(version) {
  const values = version.properties ? version.properties.filter((p) => p.key === PropertyType.ExecutesCode) : [];
  return values.length > 0 ? values[0].value === "true" : void 0;
}
function getEnabledApiProposals(version) {
  const values = version.properties ? version.properties.filter((p) => p.key === PropertyType.EnabledApiProposals) : [];
  const value = values.length > 0 && values[0].value || "";
  return value ? value.split(",") : [];
}
function getLocalizedLanguages(version) {
  const values = version.properties ? version.properties.filter((p) => p.key === PropertyType.LocalizedLanguages) : [];
  const value = values.length > 0 && values[0].value || "";
  return value ? value.split(",") : [];
}
function getSponsorLink(version) {
  return version.properties?.find((p) => p.key === PropertyType.SponsorLink)?.value;
}
function getSupportLink(version) {
  return version.properties?.find((p) => p.key === PropertyType.SupportLink)?.value;
}
function getIsPreview(flags) {
  return flags.indexOf("preview") !== -1;
}
function getTargetPlatformForExtensionVersion(version) {
  return version.targetPlatform ? $Bp(version.targetPlatform) : "undefined";
}
function getAllTargetPlatforms(rawGalleryExtension) {
  const allTargetPlatforms = $Zb(rawGalleryExtension.versions.map(getTargetPlatformForExtensionVersion));
  const isWebExtension = !!rawGalleryExtension.tags?.includes($vp);
  const webTargetPlatformIndex = allTargetPlatforms.indexOf(
    "web"
    /* TargetPlatform.WEB */
  );
  if (isWebExtension) {
    if (webTargetPlatformIndex === -1) {
      allTargetPlatforms.push(
        "web"
        /* TargetPlatform.WEB */
      );
    }
  } else {
    if (webTargetPlatformIndex !== -1) {
      allTargetPlatforms.splice(webTargetPlatformIndex, 1);
    }
  }
  return allTargetPlatforms;
}
function $Lq(versions, preferredTargetPlatform) {
  for (let index = 0; index < versions.length; index++) {
    const version = versions[index];
    if (version.version === versions[index - 1]?.version) {
      let insertionIndex = index;
      const versionTargetPlatform = getTargetPlatformForExtensionVersion(version);
      if (versionTargetPlatform === preferredTargetPlatform) {
        while (insertionIndex > 0 && versions[insertionIndex - 1].version === version.version) {
          insertionIndex--;
        }
      }
      if (insertionIndex !== index) {
        versions.splice(index, 1);
        versions.splice(insertionIndex, 0, version);
      }
    }
  }
  return versions;
}
function setTelemetry(extension, index, querySource) {
  extension.telemetryData = { index, querySource, queryActivityId: extension.queryContext?.[ACTIVITY_HEADER_NAME] };
}
function toExtension(galleryExtension, version, allTargetPlatforms, queryContext) {
  const latestVersion = galleryExtension.versions[0];
  const assets = {
    manifest: getVersionAsset(version, AssetType.Manifest),
    readme: getVersionAsset(version, AssetType.Details),
    changelog: getVersionAsset(version, AssetType.Changelog),
    license: getVersionAsset(version, AssetType.License),
    repository: getRepositoryAsset(version),
    download: getDownloadAsset(version),
    icon: getVersionAsset(version, AssetType.Icon),
    signature: getVersionAsset(version, AssetType.Signature),
    coreTranslations: getCoreTranslationAssets(version)
  };
  return {
    type: "gallery",
    identifier: {
      id: $aq(galleryExtension.publisher.publisherName, galleryExtension.extensionName),
      uuid: galleryExtension.extensionId
    },
    name: galleryExtension.extensionName,
    version: version.version,
    displayName: galleryExtension.displayName,
    publisherId: galleryExtension.publisher.publisherId,
    publisher: galleryExtension.publisher.publisherName,
    publisherDisplayName: galleryExtension.publisher.displayName,
    publisherDomain: galleryExtension.publisher.domain ? { link: galleryExtension.publisher.domain, verified: !!galleryExtension.publisher.isDomainVerified } : void 0,
    publisherSponsorLink: getSponsorLink(latestVersion),
    description: galleryExtension.shortDescription ?? "",
    installCount: getStatistic(galleryExtension.statistics, "install"),
    rating: getStatistic(galleryExtension.statistics, "averagerating"),
    ratingCount: getStatistic(galleryExtension.statistics, "ratingcount"),
    categories: galleryExtension.categories || [],
    tags: galleryExtension.tags || [],
    releaseDate: Date.parse(galleryExtension.releaseDate),
    lastUpdated: Date.parse(galleryExtension.lastUpdated),
    allTargetPlatforms,
    assets,
    properties: {
      dependencies: getExtensions(version, PropertyType.Dependency),
      extensionPack: getExtensions(version, PropertyType.ExtensionPack),
      engine: getEngine(version),
      enabledApiProposals: getEnabledApiProposals(version),
      localizedLanguages: getLocalizedLanguages(version),
      targetPlatform: getTargetPlatformForExtensionVersion(version),
      isPreReleaseVersion: isPreReleaseVersion(version),
      executesCode: executesCode(version)
    },
    hasPreReleaseVersion: isPreReleaseVersion(latestVersion),
    hasReleaseVersion: true,
    preview: getIsPreview(galleryExtension.flags),
    isSigned: !!assets.signature,
    queryContext,
    supportLink: getSupportLink(latestVersion)
  };
}
var AbstractExtensionGalleryService = class AbstractExtensionGalleryService2 {
  constructor(storageService, l, n, o, q, u, w, x) {
    this.l = l;
    this.n = n;
    this.o = o;
    this.q = q;
    this.u = u;
    this.w = w;
    this.x = x;
    const config = w.extensionsGallery;
    const isPPEEnabled = config?.servicePPEUrl && x.getValue("_extensionsGallery.enablePPE");
    this.d = isPPEEnabled ? config.servicePPEUrl : config?.serviceUrl;
    this.g = isPPEEnabled ? void 0 : config?.searchUrl;
    this.h = config?.controlUrl;
    this.k = w.extensionsEnabledWithApiProposalVersion?.map((id2) => id2.toLowerCase()) ?? [];
    this.j = $Kq(w.version, w, this.o, this.x, this.u, storageService, this.q);
  }
  y(path2 = "") {
    return `${this.d}${path2}`;
  }
  isEnabled() {
    return !!this.d;
  }
  async getExtensions(extensionInfos, arg1, arg2) {
    const options = CancellationToken.isCancellationToken(arg1) ? {} : arg1;
    const token = CancellationToken.isCancellationToken(arg1) ? arg1 : arg2;
    const result = await this.z(extensionInfos, options, token);
    const uuids = result.map((r) => r.identifier.uuid);
    const extensionInfosByName = [];
    for (const e of extensionInfos) {
      if (e.uuid && !uuids.includes(e.uuid)) {
        extensionInfosByName.push({ ...e, uuid: void 0 });
      }
    }
    if (extensionInfosByName.length) {
      this.q.publicLog2("galleryService:additionalQueryByName", {
        count: extensionInfosByName.length
      });
      const extensions = await this.z(extensionInfosByName, options, token);
      result.push(...extensions);
    }
    return result;
  }
  async z(extensionInfos, options, token) {
    const names = [];
    const ids = [], includePreReleases = [], versions = [];
    let isQueryForReleaseVersionFromPreReleaseVersion = true;
    for (const extensionInfo of extensionInfos) {
      if (extensionInfo.uuid) {
        ids.push(extensionInfo.uuid);
      } else {
        names.push(extensionInfo.id);
      }
      const includePreRelease = !!(extensionInfo.version || extensionInfo.preRelease);
      includePreReleases.push({ id: extensionInfo.id, uuid: extensionInfo.uuid, includePreRelease });
      if (extensionInfo.version) {
        versions.push({ id: extensionInfo.id, uuid: extensionInfo.uuid, version: extensionInfo.version });
      }
      isQueryForReleaseVersionFromPreReleaseVersion = isQueryForReleaseVersionFromPreReleaseVersion && (!!extensionInfo.hasPreRelease && !includePreRelease);
    }
    if (!ids.length && !names.length) {
      return [];
    }
    let query = new Query().withPage(1, extensionInfos.length);
    if (ids.length) {
      query = query.withFilter(FilterType.ExtensionId, ...ids);
    }
    if (names.length) {
      query = query.withFilter(FilterType.ExtensionName, ...names);
    }
    if (options.queryAllVersions || isQueryForReleaseVersionFromPreReleaseVersion) {
      query = query.withFlags(query.flags, Flags.IncludeVersions);
    }
    if (options.source) {
      query = query.withSource(options.source);
    }
    const { extensions } = await this.C(query, { targetPlatform: options.targetPlatform ?? CURRENT_TARGET_PLATFORM, includePreRelease: includePreReleases, versions, compatible: !!options.compatible, productVersion: options.productVersion ?? { version: this.w.version, date: this.w.date } }, token);
    if (options.source) {
      extensions.forEach((e, index) => setTelemetry(e, index, options.source));
    }
    return extensions;
  }
  async getCompatibleExtension(extension, includePreRelease, targetPlatform, productVersion = { version: this.w.version, date: this.w.date }) {
    if ($Dp(extension.allTargetPlatforms, targetPlatform)) {
      return null;
    }
    if (await this.isExtensionCompatible(extension, includePreRelease, targetPlatform)) {
      return extension;
    }
    const query = new Query().withFlags(Flags.IncludeVersions).withPage(1, 1).withFilter(FilterType.ExtensionId, extension.identifier.uuid);
    const { extensions } = await this.C(query, { targetPlatform, compatible: true, includePreRelease, productVersion }, CancellationToken.None);
    return extensions[0] || null;
  }
  async isExtensionCompatible(extension, includePreRelease, targetPlatform, productVersion = { version: this.w.version, date: this.w.date }) {
    if (!$Ep(extension.properties.targetPlatform, extension.allTargetPlatforms, targetPlatform)) {
      return false;
    }
    if (!includePreRelease && extension.properties.isPreReleaseVersion) {
      return false;
    }
    let engine = extension.properties.engine;
    if (!engine) {
      const manifest = await this.getManifest(extension, CancellationToken.None);
      if (!manifest) {
        throw new Error("Manifest was not found");
      }
      engine = manifest.engines.vscode;
    }
    if (!$oq(engine, productVersion.version, productVersion.date)) {
      return false;
    }
    if (!this.A(extension.identifier, extension.properties.enabledApiProposals)) {
      return false;
    }
    return true;
  }
  A(extensionIdentifier, enabledApiProposals) {
    if (!enabledApiProposals) {
      return true;
    }
    if (!this.k.includes(extensionIdentifier.id.toLowerCase())) {
      return true;
    }
    return $pq(enabledApiProposals);
  }
  async B(extension, rawGalleryExtensionVersion, versionType, compatible, allTargetPlatforms, targetPlatform, productVersion = { version: this.w.version, date: this.w.date }) {
    if (!$Ep(getTargetPlatformForExtensionVersion(rawGalleryExtensionVersion), allTargetPlatforms, targetPlatform)) {
      return false;
    }
    if (versionType !== "any" && isPreReleaseVersion(rawGalleryExtensionVersion) !== (versionType === "prerelease")) {
      return false;
    }
    if (compatible) {
      try {
        const engine = await this.H(extension, rawGalleryExtensionVersion);
        if (!$oq(engine, productVersion.version, productVersion.date)) {
          return false;
        }
      } catch (error) {
        this.n.error(`Error while getting the engine for the version ${rawGalleryExtensionVersion.version}.`, $kb(error));
        return false;
      }
    }
    return true;
  }
  async query(options, token) {
    let text = options.text || "";
    const pageSize = options.pageSize ?? 50;
    let query = new Query().withPage(1, pageSize);
    if (text) {
      text = text.replace(/\bcategory:("([^"]*)"|([^"]\S*))(\s+|\b|$)/g, (_, quotedCategory, category) => {
        query = query.withFilter(FilterType.Category, category || quotedCategory);
        return "";
      });
      text = text.replace(/\btag:("([^"]*)"|([^"]\S*))(\s+|\b|$)/g, (_, quotedTag, tag) => {
        query = query.withFilter(FilterType.Tag, tag || quotedTag);
        return "";
      });
      text = text.replace(/\bfeatured(\s+|\b|$)/g, () => {
        query = query.withFilter(FilterType.Featured);
        return "";
      });
      text = text.trim();
      if (text) {
        text = text.length < 200 ? text : text.substring(0, 200);
        query = query.withFilter(FilterType.SearchText, text);
      }
      query = query.withSortBy(
        0
        /* SortBy.NoneOrRelevance */
      );
    } else if (options.ids) {
      query = query.withFilter(FilterType.ExtensionId, ...options.ids);
    } else if (options.names) {
      query = query.withFilter(FilterType.ExtensionName, ...options.names);
    } else {
      query = query.withSortBy(
        4
        /* SortBy.InstallCount */
      );
    }
    if (typeof options.sortBy === "number") {
      query = query.withSortBy(options.sortBy);
    }
    if (typeof options.sortOrder === "number") {
      query = query.withSortOrder(options.sortOrder);
    }
    if (options.source) {
      query = query.withSource(options.source);
    }
    const runQuery = async (query2, token2) => {
      const { extensions: extensions2, total: total2 } = await this.C(query2, { targetPlatform: CURRENT_TARGET_PLATFORM, compatible: false, includePreRelease: !!options.includePreRelease, productVersion: options.productVersion ?? { version: this.w.version, date: this.w.date } }, token2);
      extensions2.forEach((e, index) => setTelemetry(e, (query2.pageNumber - 1) * query2.pageSize + index, options.source));
      return { extensions: extensions2, total: total2 };
    };
    const { extensions, total } = await runQuery(query, token);
    const getPage = async (pageIndex, ct) => {
      if (ct.isCancellationRequested) {
        throw new $fb();
      }
      const { extensions: extensions2 } = await runQuery(query.withPage(pageIndex + 1), ct);
      return extensions2;
    };
    return { firstPage: extensions, total, pageSize: query.pageSize, getPage };
  }
  async C(query, criteria, token) {
    const flags = query.flags;
    if (!!(query.flags & Flags.IncludeLatestVersionOnly) && !!(query.flags & Flags.IncludeVersions)) {
      query = query.withFlags(query.flags & ~Flags.IncludeVersions, Flags.IncludeLatestVersionOnly);
    }
    if (!(query.flags & Flags.IncludeLatestVersionOnly) && !(query.flags & Flags.IncludeVersions)) {
      query = query.withFlags(query.flags, Flags.IncludeLatestVersionOnly);
    }
    if (criteria.versions?.length) {
      query = query.withFlags(query.flags & ~Flags.IncludeLatestVersionOnly, Flags.IncludeVersions);
    }
    query = query.withFlags(query.flags, Flags.IncludeAssetUri, Flags.IncludeCategoryAndTags, Flags.IncludeFiles, Flags.IncludeStatistics, Flags.IncludeVersionProperties);
    const { galleryExtensions: rawGalleryExtensions, total, context } = await this.E(query, token);
    const hasAllVersions = !(query.flags & Flags.IncludeLatestVersionOnly);
    if (hasAllVersions) {
      const extensions = [];
      for (const rawGalleryExtension of rawGalleryExtensions) {
        const extension = await this.D(rawGalleryExtension, criteria, context);
        if (extension) {
          extensions.push(extension);
        }
      }
      return { extensions, total };
    }
    const result = [];
    const needAllVersions = /* @__PURE__ */ new Map();
    for (let index = 0; index < rawGalleryExtensions.length; index++) {
      const rawGalleryExtension = rawGalleryExtensions[index];
      const extensionIdentifier = { id: $aq(rawGalleryExtension.publisher.publisherName, rawGalleryExtension.extensionName), uuid: rawGalleryExtension.extensionId };
      const includePreRelease = $Eg(criteria.includePreRelease) ? criteria.includePreRelease : !!criteria.includePreRelease.find((extensionIdentifierWithPreRelease) => $8p(extensionIdentifierWithPreRelease, extensionIdentifier))?.includePreRelease;
      if (criteria.compatible && $Dp(getAllTargetPlatforms(rawGalleryExtension), criteria.targetPlatform)) {
        continue;
      }
      const extension = await this.D(rawGalleryExtension, criteria, context);
      if (!extension || extension.properties.isPreReleaseVersion && (!includePreRelease || !extension.hasReleaseVersion) || !extension.properties.isPreReleaseVersion && extension.properties.targetPlatform !== criteria.targetPlatform && extension.hasPreReleaseVersion) {
        needAllVersions.set(rawGalleryExtension.extensionId, index);
      } else {
        result.push([index, extension]);
      }
    }
    if (needAllVersions.size) {
      const stopWatch = new $xe();
      const query2 = new Query().withFlags(flags & ~Flags.IncludeLatestVersionOnly, Flags.IncludeVersions).withPage(1, needAllVersions.size).withFilter(FilterType.ExtensionId, ...needAllVersions.keys());
      const { extensions } = await this.C(query2, criteria, token);
      this.q.publicLog2("galleryService:additionalQuery", {
        duration: stopWatch.elapsed(),
        count: needAllVersions.size
      });
      for (const extension of extensions) {
        const index = needAllVersions.get(extension.identifier.uuid);
        result.push([index, extension]);
      }
    }
    return { extensions: result.sort((a, b) => a[0] - b[0]).map(([, extension]) => extension), total };
  }
  async D(rawGalleryExtension, criteria, queryContext) {
    const extensionIdentifier = { id: $aq(rawGalleryExtension.publisher.publisherName, rawGalleryExtension.extensionName), uuid: rawGalleryExtension.extensionId };
    const version = criteria.versions?.find((extensionIdentifierWithVersion) => $8p(extensionIdentifierWithVersion, extensionIdentifier))?.version;
    const includePreRelease = $Eg(criteria.includePreRelease) ? criteria.includePreRelease : !!criteria.includePreRelease.find((extensionIdentifierWithPreRelease) => $8p(extensionIdentifierWithPreRelease, extensionIdentifier))?.includePreRelease;
    const allTargetPlatforms = getAllTargetPlatforms(rawGalleryExtension);
    const rawGalleryExtensionVersions = $Lq(rawGalleryExtension.versions, criteria.targetPlatform);
    if (criteria.compatible && $Dp(allTargetPlatforms, criteria.targetPlatform)) {
      return null;
    }
    for (let index = 0; index < rawGalleryExtensionVersions.length; index++) {
      const rawGalleryExtensionVersion = rawGalleryExtensionVersions[index];
      if (version && rawGalleryExtensionVersion.version !== version) {
        continue;
      }
      if (await this.B(extensionIdentifier.id, rawGalleryExtensionVersion, includePreRelease ? "any" : "release", criteria.compatible, allTargetPlatforms, criteria.targetPlatform, criteria.productVersion)) {
        if (criteria.compatible && !this.A(extensionIdentifier, getEnabledApiProposals(rawGalleryExtensionVersion))) {
          continue;
        }
        return toExtension(rawGalleryExtension, rawGalleryExtensionVersion, allTargetPlatforms, queryContext);
      }
      if (version && rawGalleryExtensionVersion.version === version) {
        return null;
      }
    }
    if (version || criteria.compatible) {
      return null;
    }
    return toExtension(rawGalleryExtension, rawGalleryExtension.versions[0], allTargetPlatforms);
  }
  async E(query, token) {
    if (!this.isEnabled()) {
      throw new Error("No extension gallery service configured.");
    }
    query = query.withFlags(query.flags, Flags.ExcludeNonValidated).withFilter(FilterType.Target, "Microsoft.VisualStudio.Code").withFilter(FilterType.ExcludeWithFlags, flagsToString(Flags.Unpublished));
    const commonHeaders = await this.j;
    const data = JSON.stringify(query.raw);
    const headers = {
      ...commonHeaders,
      "Content-Type": "application/json",
      "Accept": "application/json;api-version=3.0-preview.1",
      "Accept-Encoding": "gzip",
      "Content-Length": String(data.length)
    };
    const stopWatch = new $xe();
    let context, errorCode, total = 0;
    try {
      context = await this.l.request({
        type: "POST",
        url: this.g && query.criteria.some((c) => c.filterType === FilterType.SearchText) ? this.g : this.y("/extensionquery"),
        data,
        headers
      }, token);
      if (context.res.statusCode && context.res.statusCode >= 400 && context.res.statusCode < 500) {
        return { galleryExtensions: [], total };
      }
      const result = await $wq(context);
      if (result) {
        const r = result.results[0];
        const galleryExtensions = r.extensions;
        const resultCount = r.resultMetadata && r.resultMetadata.filter((m) => m.metadataType === "ResultCount")[0];
        total = resultCount && resultCount.metadataItems.filter((i) => i.name === "TotalCount")[0].count || 0;
        return {
          galleryExtensions,
          total,
          context: context.res.headers["activityid"] ? {
            [ACTIVITY_HEADER_NAME]: context.res.headers["activityid"]
          } : {}
        };
      }
      return { galleryExtensions: [], total };
    } catch (e) {
      if ($eb(e)) {
        errorCode = "Cancelled";
        throw e;
      } else {
        const errorMessage = $kb(e);
        errorCode = $rp(e) ? "Offline" : errorMessage.startsWith("XHR timeout") ? "Timeout" : "Failed";
        throw new $Hp(errorMessage, errorCode);
      }
    } finally {
      this.q.publicLog2("galleryService:query", {
        ...query.telemetryData,
        requestBodySize: String(data.length),
        duration: stopWatch.elapsed(),
        success: !!context && $sq(context),
        responseBodySize: context?.res.headers["Content-Length"],
        statusCode: context ? String(context.res.statusCode) : void 0,
        errorCode,
        count: String(total)
      });
    }
  }
  async reportStatistic(publisher, name, version, type2) {
    if (!this.isEnabled()) {
      return void 0;
    }
    const url = $r ? this.y(`/itemName/${publisher}.${name}/version/${version}/statType/${type2 === "install" ? "1" : "3"}/vscodewebextension`) : this.y(`/publishers/${publisher}/extensions/${name}/${version}/stats?statType=${type2}`);
    const Accept = $r ? "api-version=6.1-preview.1" : "*/*;api-version=4.0-preview.1";
    const commonHeaders = await this.j;
    const headers = { ...commonHeaders, Accept };
    try {
      await this.l.request({
        type: "POST",
        url,
        headers
      }, CancellationToken.None);
    } catch (error) {
    }
  }
  async download(extension, location, operation) {
    this.n.trace("ExtensionGalleryService#download", extension.identifier.id);
    const data = $dq(extension);
    const startTime = (/* @__PURE__ */ new Date()).getTime();
    const operationParam = operation === 2 ? "install" : operation === 3 ? "update" : "";
    const downloadAsset = operationParam ? {
      uri: `${extension.assets.download.uri}${URI.parse(extension.assets.download.uri).query ? "&" : "?"}${operationParam}=true`,
      fallbackUri: `${extension.assets.download.fallbackUri}${URI.parse(extension.assets.download.fallbackUri).query ? "&" : "?"}${operationParam}=true`
    } : extension.assets.download;
    const headers = extension.queryContext?.[ACTIVITY_HEADER_NAME] ? { [ACTIVITY_HEADER_NAME]: extension.queryContext[ACTIVITY_HEADER_NAME] } : void 0;
    const context = await this.G(extension.identifier.id, downloadAsset, AssetType.VSIX, headers ? { headers } : void 0);
    try {
      await this.u.writeFile(location, context.stream);
    } catch (error) {
      try {
        await this.u.del(location);
      } catch (e) {
        this.n.warn(`Error while deleting the file ${location.toString()}`, $kb(e));
      }
      throw new $Hp(
        $kb(error),
        "DownloadFailedWriting"
        /* ExtensionGalleryErrorCode.DownloadFailedWriting */
      );
    }
    this.q.publicLog("galleryService:downloadVSIX", { ...data, duration: (/* @__PURE__ */ new Date()).getTime() - startTime });
  }
  async downloadSignatureArchive(extension, location) {
    if (!extension.assets.signature) {
      throw new Error("No signature asset found");
    }
    this.n.trace("ExtensionGalleryService#downloadSignatureArchive", extension.identifier.id);
    const context = await this.G(extension.identifier.id, extension.assets.signature, AssetType.Signature);
    try {
      await this.u.writeFile(location, context.stream);
    } catch (error) {
      try {
        await this.u.del(location);
      } catch (e) {
        this.n.warn(`Error while deleting the file ${location.toString()}`, $kb(e));
      }
      throw new $Hp(
        $kb(error),
        "DownloadFailedWriting"
        /* ExtensionGalleryErrorCode.DownloadFailedWriting */
      );
    }
  }
  async getReadme(extension, token) {
    if (extension.assets.readme) {
      const context = await this.G(extension.identifier.id, extension.assets.readme, AssetType.Details, {}, token);
      const content = await $vq(context);
      return content || "";
    }
    return "";
  }
  async getManifest(extension, token) {
    if (extension.assets.manifest) {
      const context = await this.G(extension.identifier.id, extension.assets.manifest, AssetType.Manifest, {}, token);
      const text = await $vq(context);
      return text ? JSON.parse(text) : null;
    }
    return null;
  }
  async F(extension, rawExtensionVersion, token) {
    const manifestAsset = getVersionAsset(rawExtensionVersion, AssetType.Manifest);
    if (!manifestAsset) {
      throw new Error("Manifest was not found");
    }
    const headers = { "Accept-Encoding": "gzip" };
    const context = await this.G(extension, manifestAsset, AssetType.Manifest, { headers });
    return await $wq(context);
  }
  async getCoreTranslation(extension, languageId) {
    const asset = extension.assets.coreTranslations.filter((t) => t[0] === languageId.toUpperCase())[0];
    if (asset) {
      const context = await this.G(extension.identifier.id, asset[1], asset[0]);
      const text = await $vq(context);
      return text ? JSON.parse(text) : null;
    }
    return null;
  }
  async getChangelog(extension, token) {
    if (extension.assets.changelog) {
      const context = await this.G(extension.identifier.id, extension.assets.changelog, AssetType.Changelog, {}, token);
      const content = await $vq(context);
      return content || "";
    }
    return "";
  }
  async getAllCompatibleVersions(extensionIdentifier, includePreRelease, targetPlatform) {
    let query = new Query().withFlags(Flags.IncludeVersions, Flags.IncludeCategoryAndTags, Flags.IncludeFiles, Flags.IncludeVersionProperties).withPage(1, 1);
    if (extensionIdentifier.uuid) {
      query = query.withFilter(FilterType.ExtensionId, extensionIdentifier.uuid);
    } else {
      query = query.withFilter(FilterType.ExtensionName, extensionIdentifier.id);
    }
    const { galleryExtensions } = await this.E(query, CancellationToken.None);
    if (!galleryExtensions.length) {
      return [];
    }
    const allTargetPlatforms = getAllTargetPlatforms(galleryExtensions[0]);
    if ($Dp(allTargetPlatforms, targetPlatform)) {
      return [];
    }
    const validVersions = [];
    await Promise.all(galleryExtensions[0].versions.map(async (version) => {
      try {
        if (await this.B(extensionIdentifier.id, version, includePreRelease ? "any" : "release", true, allTargetPlatforms, targetPlatform) && this.A(extensionIdentifier, getEnabledApiProposals(version))) {
          validVersions.push(version);
        }
      } catch (error) {
      }
    }));
    const result = [];
    const seen = /* @__PURE__ */ new Set();
    for (const version of $Lq(validVersions, targetPlatform)) {
      if (!seen.has(version.version)) {
        seen.add(version.version);
        result.push({ version: version.version, date: version.lastUpdated, isPreReleaseVersion: isPreReleaseVersion(version) });
      }
    }
    return result;
  }
  async G(extension, asset, assetType, options = {}, token = CancellationToken.None) {
    const commonHeaders = await this.j;
    const baseOptions = { type: "GET" };
    const headers = { ...commonHeaders, ...options.headers || {} };
    options = { ...options, ...baseOptions, headers };
    const url = asset.uri;
    const fallbackUrl = asset.fallbackUri;
    const firstOptions = { ...options, url };
    try {
      const context = await this.l.request(firstOptions, token);
      if (context.res.statusCode === 200) {
        return context;
      }
      const message = await $vq(context);
      throw new Error(`Expected 200, got back ${context.res.statusCode} instead.

${message}`);
    } catch (err) {
      if ($eb(err)) {
        throw err;
      }
      const message = $kb(err);
      this.q.publicLog2("galleryService:cdnFallback", { extension, assetType, message });
      const fallbackOptions = { ...options, url: fallbackUrl };
      return this.l.request(fallbackOptions, token);
    }
  }
  async H(extension, rawExtensionVersion) {
    let engine = getEngine(rawExtensionVersion);
    if (!engine) {
      this.q.publicLog2("galleryService:engineFallback", { extension, version: rawExtensionVersion.version });
      const manifest = await this.F(extension, rawExtensionVersion, CancellationToken.None);
      if (!manifest) {
        throw new Error("Manifest was not found");
      }
      engine = manifest.engines.vscode;
    }
    return engine;
  }
  async getExtensionsControlManifest() {
    if (!this.isEnabled()) {
      throw new Error("No extension gallery service configured.");
    }
    if (!this.h) {
      return { malicious: [], deprecated: {}, search: [] };
    }
    const context = await this.l.request({ type: "GET", url: this.h }, CancellationToken.None);
    if (context.res.statusCode !== 200) {
      throw new Error("Could not get extensions report.");
    }
    const result = await $wq(context);
    const malicious = [];
    const deprecated = {};
    const search = [];
    const extensionsEnabledWithPreRelease = [];
    if (result) {
      for (const id2 of result.malicious) {
        malicious.push({ id: id2 });
      }
      if (result.migrateToPreRelease) {
        for (const [unsupportedPreReleaseExtensionId, preReleaseExtensionInfo] of Object.entries(result.migrateToPreRelease)) {
          if (!preReleaseExtensionInfo.engine || $oq(preReleaseExtensionInfo.engine, this.w.version, this.w.date)) {
            deprecated[unsupportedPreReleaseExtensionId.toLowerCase()] = {
              disallowInstall: true,
              extension: {
                id: preReleaseExtensionInfo.id,
                displayName: preReleaseExtensionInfo.displayName,
                autoMigrate: { storage: !!preReleaseExtensionInfo.migrateStorage },
                preRelease: true
              }
            };
          }
        }
      }
      if (result.deprecated) {
        for (const [deprecatedExtensionId, deprecationInfo] of Object.entries(result.deprecated)) {
          if (deprecationInfo) {
            deprecated[deprecatedExtensionId.toLowerCase()] = $Eg(deprecationInfo) ? {} : deprecationInfo;
          }
        }
      }
      if (result.search) {
        for (const s of result.search) {
          search.push(s);
        }
      }
      if (Array.isArray(result.extensionsEnabledWithPreRelease)) {
        for (const id2 of result.extensionsEnabledWithPreRelease) {
          extensionsEnabledWithPreRelease.push(id2.toLowerCase());
        }
      }
    }
    return { malicious, deprecated, search, extensionsEnabledWithPreRelease };
  }
};
AbstractExtensionGalleryService = __decorate([
  __param(1, $qq),
  __param(2, $uk),
  __param(3, $7i),
  __param(4, $tm),
  __param(5, $ul),
  __param(6, $Nk),
  __param(7, $tj)
], AbstractExtensionGalleryService);
var $Mq = class $Mq2 extends AbstractExtensionGalleryService {
  constructor(storageService, requestService, logService, environmentService, telemetryService, fileService, productService, configurationService) {
    super(storageService, requestService, logService, environmentService, telemetryService, fileService, productService, configurationService);
  }
};
$Mq = __decorate([
  __param(0, $Dq),
  __param(1, $qq),
  __param(2, $uk),
  __param(3, $7i),
  __param(4, $tm),
  __param(5, $ul),
  __param(6, $Nk),
  __param(7, $tj)
], $Mq);
var $Nq = class $Nq2 extends AbstractExtensionGalleryService {
  constructor(requestService, logService, environmentService, telemetryService, fileService, productService, configurationService) {
    super(void 0, requestService, logService, environmentService, telemetryService, fileService, productService, configurationService);
  }
};
$Nq = __decorate([
  __param(0, $qq),
  __param(1, $uk),
  __param(2, $7i),
  __param(3, $tm),
  __param(4, $ul),
  __param(5, $Nk),
  __param(6, $tj)
], $Nq);

// 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/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((resolve) => {
        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}`);
          resolve(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((resolve, 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();
        resolve(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 fs8 = (await import(`${"fs"}`)).default;
      const vm = (await import(`${"vm"}`)).default;
      const module4 = (await import(`${"module"}`)).default;
      const filePath = URI.parse(scriptSrc).fsPath;
      const content = fs8.readFileSync(filePath).toString();
      const scriptSource = module4.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 module4;
    try {
      module4 = 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 module4.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/base/common/uriIpc.js
var $9n = new class {
  transformIncoming(uri) {
    return uri;
  }
  transformOutgoing(uri) {
    return uri;
  }
  transformOutgoingURI(uri) {
    return uri;
  }
  transformOutgoingScheme(scheme) {
    return scheme;
  }
}();
function _transformIncomingURIs(obj, transformer, revive, depth) {
  if (!obj || depth > 200) {
    return null;
  }
  if (typeof obj === "object") {
    if (obj.$mid === 1) {
      return revive ? URI.revive(transformer.transformIncoming(obj)) : transformer.transformIncoming(obj);
    }
    if (obj instanceof $7e) {
      return null;
    }
    for (const key in obj) {
      if (Object.hasOwnProperty.call(obj, key)) {
        const r = _transformIncomingURIs(obj[key], transformer, revive, depth + 1);
        if (r !== null) {
          obj[key] = r;
        }
      }
    }
  }
  return null;
}
function $_n(obj, transformer) {
  const result = _transformIncomingURIs(obj, transformer, true, 0);
  if (result === null) {
    return obj;
  }
  return result;
}

// out-build/vs/platform/extensionManagement/common/extensionManagementIpc.js
function transformIncomingURI(uri, transformer) {
  return uri ? URI.revive(transformer ? transformer.transformIncoming(uri) : uri) : void 0;
}
function transformOutgoingURI(uri, transformer) {
  return transformer ? transformer.transformOutgoingURI(uri) : uri;
}
function transformIncomingExtension(extension, transformer) {
  transformer = transformer ? transformer : $9n;
  const manifest = extension.manifest;
  const transformed = $_n({ ...extension, ...{ manifest: void 0 } }, transformer);
  return { ...transformed, ...{ manifest } };
}
function transformIncomingOptions(options, transformer) {
  return options?.profileLocation ? $_n(options, transformer ?? $9n) : options;
}
function transformOutgoingExtension(extension, transformer) {
  return transformer ? $Bo(extension, (value) => value instanceof URI ? transformer.transformOutgoingURI(value) : void 0) : extension;
}
var $Tq = class {
  constructor(a, b) {
    this.a = a;
    this.b = b;
    this.onInstallExtension = Event.buffer(a.onInstallExtension, true);
    this.onDidInstallExtensions = Event.buffer(a.onDidInstallExtensions, true);
    this.onUninstallExtension = Event.buffer(a.onUninstallExtension, true);
    this.onDidUninstallExtension = Event.buffer(a.onDidUninstallExtension, true);
    this.onDidUpdateExtensionMetadata = Event.buffer(a.onDidUpdateExtensionMetadata, true);
  }
  listen(context, event) {
    const uriTransformer = this.b(context);
    switch (event) {
      case "onInstallExtension": {
        return Event.map(this.onInstallExtension, (e) => {
          return {
            ...e,
            profileLocation: e.profileLocation ? transformOutgoingURI(e.profileLocation, uriTransformer) : e.profileLocation
          };
        });
      }
      case "onDidInstallExtensions": {
        return Event.map(this.onDidInstallExtensions, (results) => results.map((i) => ({
          ...i,
          local: i.local ? transformOutgoingExtension(i.local, uriTransformer) : i.local,
          profileLocation: i.profileLocation ? transformOutgoingURI(i.profileLocation, uriTransformer) : i.profileLocation
        })));
      }
      case "onUninstallExtension": {
        return Event.map(this.onUninstallExtension, (e) => {
          return {
            ...e,
            profileLocation: e.profileLocation ? transformOutgoingURI(e.profileLocation, uriTransformer) : e.profileLocation
          };
        });
      }
      case "onDidUninstallExtension": {
        return Event.map(this.onDidUninstallExtension, (e) => {
          return {
            ...e,
            profileLocation: e.profileLocation ? transformOutgoingURI(e.profileLocation, uriTransformer) : e.profileLocation
          };
        });
      }
      case "onDidUpdateExtensionMetadata": {
        return Event.map(this.onDidUpdateExtensionMetadata, (e) => {
          return {
            local: transformOutgoingExtension(e.local, uriTransformer),
            profileLocation: transformOutgoingURI(e.profileLocation, uriTransformer)
          };
        });
      }
    }
    throw new Error("Invalid listen");
  }
  async call(context, command, args) {
    const uriTransformer = this.b(context);
    switch (command) {
      case "zip": {
        const extension = transformIncomingExtension(args[0], uriTransformer);
        const uri = await this.a.zip(extension);
        return transformOutgoingURI(uri, uriTransformer);
      }
      case "install": {
        return this.a.install(transformIncomingURI(args[0], uriTransformer), transformIncomingOptions(args[1], uriTransformer));
      }
      case "installFromLocation": {
        return this.a.installFromLocation(transformIncomingURI(args[0], uriTransformer), transformIncomingURI(args[1], uriTransformer));
      }
      case "installExtensionsFromProfile": {
        return this.a.installExtensionsFromProfile(args[0], transformIncomingURI(args[1], uriTransformer), transformIncomingURI(args[2], uriTransformer));
      }
      case "getManifest": {
        return this.a.getManifest(transformIncomingURI(args[0], uriTransformer));
      }
      case "getTargetPlatform": {
        return this.a.getTargetPlatform();
      }
      case "canInstall": {
        return this.a.canInstall(args[0]);
      }
      case "installFromGallery": {
        return this.a.installFromGallery(args[0], transformIncomingOptions(args[1], uriTransformer));
      }
      case "installGalleryExtensions": {
        const arg = args[0];
        return this.a.installGalleryExtensions(arg.map(({ extension, options }) => ({ extension, options: transformIncomingOptions(options, uriTransformer) ?? {} })));
      }
      case "uninstall": {
        return this.a.uninstall(transformIncomingExtension(args[0], uriTransformer), transformIncomingOptions(args[1], uriTransformer));
      }
      case "uninstallExtensions": {
        const arg = args[0];
        return this.a.uninstallExtensions(arg.map(({ extension, options }) => ({ extension: transformIncomingExtension(extension, uriTransformer), options: transformIncomingOptions(options, uriTransformer) })));
      }
      case "reinstallFromGallery": {
        return this.a.reinstallFromGallery(transformIncomingExtension(args[0], uriTransformer));
      }
      case "getInstalled": {
        const extensions = await this.a.getInstalled(args[0], transformIncomingURI(args[1], uriTransformer), args[2]);
        return extensions.map((e) => transformOutgoingExtension(e, uriTransformer));
      }
      case "toggleAppliationScope": {
        const extension = await this.a.toggleAppliationScope(transformIncomingExtension(args[0], uriTransformer), transformIncomingURI(args[1], uriTransformer));
        return transformOutgoingExtension(extension, uriTransformer);
      }
      case "copyExtensions": {
        return this.a.copyExtensions(transformIncomingURI(args[0], uriTransformer), transformIncomingURI(args[1], uriTransformer));
      }
      case "updateMetadata": {
        const e = await this.a.updateMetadata(transformIncomingExtension(args[0], uriTransformer), args[1], transformIncomingURI(args[2], uriTransformer));
        return transformOutgoingExtension(e, uriTransformer);
      }
      case "resetPinnedStateForAllUserExtensions": {
        return this.a.resetPinnedStateForAllUserExtensions(args[0]);
      }
      case "getExtensionsControlManifest": {
        return this.a.getExtensionsControlManifest();
      }
      case "download": {
        return this.a.download(args[0], args[1], args[2]);
      }
      case "cleanUp": {
        return this.a.cleanUp();
      }
    }
    throw new Error("Invalid call");
  }
};
var $Vq = class {
  constructor(a) {
    this.a = a;
  }
  listen(context, event) {
    throw new Error("Invalid listen");
  }
  call(context, command, args) {
    switch (command) {
      case "getConfigBasedTips":
        return this.a.getConfigBasedTips(URI.revive(args[0]));
      case "getImportantExecutableBasedTips":
        return this.a.getImportantExecutableBasedTips();
      case "getOtherExecutableBasedTips":
        return this.a.getOtherExecutableBasedTips();
    }
    throw new Error("Invalid call");
  }
};

// out-build/vs/platform/extensionManagement/node/extensionManagementService.js
import * as fs5 from "fs";

// out-build/vs/base/node/zip.js
import { createWriteStream, promises as promises5 } from "fs";
var $Wq = "end of central directory record signature not found";
var CORRUPT_ZIP_PATTERN = new RegExp($Wq);
var $Xq = class extends Error {
  constructor(type2, cause) {
    let message = cause.message;
    switch (type2) {
      case "CorruptZip":
        message = `Corrupt ZIP: ${message}`;
        break;
    }
    super(message);
    this.type = type2;
    this.cause = cause;
  }
};
function modeFromEntry(entry) {
  const attr = entry.externalFileAttributes >> 16 || 33188;
  return [
    448,
    56,
    7
    /* S_IRWXO */
  ].map((mask) => attr & mask).reduce(
    (a, b) => a + b,
    attr & 61440
    /* S_IFMT */
  );
}
function toExtractError(err) {
  if (err instanceof $Xq) {
    return err;
  }
  let type2 = void 0;
  if (CORRUPT_ZIP_PATTERN.test(err.message)) {
    type2 = "CorruptZip";
  }
  return new $Xq(type2, err);
}
function extractEntry(stream, fileName, mode, targetPath, options, token) {
  const dirName = $yc(fileName);
  const targetDirName = $vc(targetPath, dirName);
  if (!targetDirName.startsWith(targetPath)) {
    return Promise.reject(new Error(localize(143, null, fileName)));
  }
  const targetFileName = $vc(targetPath, fileName);
  let istream;
  token.onCancellationRequested(() => {
    istream?.destroy();
  });
  return Promise.resolve(promises5.mkdir(targetDirName, { recursive: true })).then(() => new Promise((c, e) => {
    if (token.isCancellationRequested) {
      return;
    }
    try {
      istream = createWriteStream(targetFileName, { mode });
      istream.once("close", () => c());
      istream.once("error", e);
      stream.once("error", e);
      stream.pipe(istream);
    } catch (error) {
      e(error);
    }
  }));
}
function extractZip(zipfile, targetPath, options, token) {
  let last = $Mh(() => Promise.resolve());
  let extractedEntriesCount = 0;
  const listener = token.onCancellationRequested(() => {
    last.cancel();
    zipfile.close();
  });
  return new Promise((c, e) => {
    const throttler = new $Uh();
    const readNextEntry = (token2) => {
      if (token2.isCancellationRequested) {
        return;
      }
      extractedEntriesCount++;
      zipfile.readEntry();
    };
    zipfile.once("error", e);
    zipfile.once("close", () => last.then(() => {
      if (token.isCancellationRequested || zipfile.entryCount === extractedEntriesCount) {
        c();
      } else {
        e(new $Xq("Incomplete", new Error(localize(144, null, extractedEntriesCount, zipfile.entryCount))));
      }
    }, e));
    zipfile.readEntry();
    zipfile.on("entry", (entry) => {
      if (token.isCancellationRequested) {
        return;
      }
      if (!options.sourcePathRegex.test(entry.fileName)) {
        readNextEntry(token);
        return;
      }
      const fileName = entry.fileName.replace(options.sourcePathRegex, "");
      if (/\/$/.test(fileName)) {
        const targetFileName = $vc(targetPath, fileName);
        last = $Mh((token2) => promises5.mkdir(targetFileName, { recursive: true }).then(() => readNextEntry(token2)).then(void 0, e));
        return;
      }
      const stream = openZipStream(zipfile, entry);
      const mode = modeFromEntry(entry);
      last = $Mh((token2) => throttler.queue(() => stream.then((stream2) => extractEntry(stream2, fileName, mode, targetPath, options, token2).then(() => readNextEntry(token2)))).then(null, e));
    });
  }).finally(() => listener.dispose());
}
async function openZip(zipFile, lazy = false) {
  const { open: open2 } = await import("yauzl");
  return new Promise((resolve, reject) => {
    open2(zipFile, lazy ? { lazyEntries: true } : void 0, (error, zipfile) => {
      if (error) {
        reject(toExtractError(error));
      } else {
        resolve($Jg(zipfile));
      }
    });
  });
}
function openZipStream(zipFile, entry) {
  return new Promise((resolve, reject) => {
    zipFile.openReadStream(entry, (error, stream) => {
      if (error) {
        reject(toExtractError(error));
      } else {
        resolve($Jg(stream));
      }
    });
  });
}
async function zip(zipPath, files) {
  const { ZipFile } = await import("yazl");
  return new Promise((c, e) => {
    const zip2 = new ZipFile();
    files.forEach((f) => {
      if (f.contents) {
        zip2.addBuffer(typeof f.contents === "string" ? Buffer.from(f.contents, "utf8") : f.contents, f.path);
      } else if (f.localPath) {
        zip2.addFile(f.localPath, f.path);
      }
    });
    zip2.end();
    const zipStream = createWriteStream(zipPath);
    zip2.outputStream.pipe(zipStream);
    zip2.outputStream.once("error", e);
    zipStream.once("error", e);
    zipStream.once("finish", () => c(zipPath));
  });
}
function $Zq(zipPath, targetPath, options = {}, token) {
  const sourcePathRegex = new RegExp(options.sourcePath ? `^${options.sourcePath}` : "");
  let promise = openZip(zipPath, true);
  if (options.overwrite) {
    promise = promise.then((zipfile) => Promises2.rm(targetPath).then(() => zipfile));
  }
  return promise.then((zipfile) => extractZip(zipfile, targetPath, { sourcePathRegex }, token));
}
function read2(zipPath, filePath) {
  return openZip(zipPath).then((zipfile) => {
    return new Promise((c, e) => {
      zipfile.on("entry", (entry) => {
        if (entry.fileName === filePath) {
          openZipStream(zipfile, entry).then((stream) => c(stream), (err) => e(err));
        }
      });
      zipfile.once("close", () => e(new Error(localize(145, null, filePath))));
    });
  });
}
function $1q(zipPath, filePath) {
  return read2(zipPath, filePath).then((stream) => {
    return new Promise((c, e) => {
      const buffers = [];
      stream.once("error", e);
      stream.on("data", (b) => buffers.push(b));
      stream.on("end", () => c(Buffer.concat(buffers)));
    });
  });
}

// out-build/vs/platform/extensionManagement/common/abstractExtensionManagementService.js
var $2q = class $2q2 extends $0c {
  get onInstallExtension() {
    return this.n.event;
  }
  get onDidInstallExtensions() {
    return this.s.event;
  }
  get onUninstallExtension() {
    return this.t.event;
  }
  get onDidUninstallExtension() {
    return this.u.event;
  }
  get onDidUpdateExtensionMetadata() {
    return this.w.event;
  }
  constructor(z, C, D, F, G, H) {
    super();
    this.z = z;
    this.C = C;
    this.D = D;
    this.F = F;
    this.G = G;
    this.H = H;
    this.h = 0;
    this.j = /* @__PURE__ */ new Map();
    this.m = /* @__PURE__ */ new Map();
    this.n = this.B(new $De());
    this.s = this.B(new $De());
    this.t = this.B(new $De());
    this.u = this.B(new $De());
    this.w = this.B(new $De());
    this.y = [];
    this.B($8c(() => {
      this.j.forEach(({ task }) => task.cancel());
      this.m.forEach((promise) => promise.cancel());
      this.j.clear();
      this.m.clear();
    }));
  }
  async canInstall(extension) {
    const currentTargetPlatform = await this.getTargetPlatform();
    return extension.allTargetPlatforms.some((targetPlatform) => $Ep(targetPlatform, extension.allTargetPlatforms, currentTargetPlatform));
  }
  async installFromGallery(extension, options = {}) {
    try {
      const results = await this.installGalleryExtensions([{ extension, options }]);
      const result = results.find(({ identifier }) => $8p(identifier, extension.identifier));
      if (result?.local) {
        return result?.local;
      }
      if (result?.error) {
        throw result.error;
      }
      throw new $Ip(
        `Unknown error while installing extension ${extension.identifier.id}`,
        "Unknown"
        /* ExtensionManagementErrorCode.Unknown */
      );
    } catch (error) {
      throw $3q(error);
    }
  }
  async installGalleryExtensions(extensions) {
    if (!this.z.isEnabled()) {
      throw new $Ip(
        localize(1777, null),
        "NotAllowed"
        /* ExtensionManagementErrorCode.NotAllowed */
      );
    }
    const results = [];
    const installableExtensions = [];
    await Promise.allSettled(extensions.map(async ({ extension, options }) => {
      try {
        const compatible = await this.O(extension, !!options?.installGivenVersion, !!options?.installPreReleaseVersion, options.productVersion ?? { version: this.G.version, date: this.G.date });
        installableExtensions.push({ ...compatible, options });
      } catch (error) {
        results.push({ identifier: extension.identifier, operation: 2, source: extension, error, profileLocation: options.profileLocation ?? this.X() });
      }
    }));
    if (installableExtensions.length) {
      results.push(...await this.I(installableExtensions));
    }
    return results;
  }
  async uninstall(extension, options) {
    this.F.trace("ExtensionManagementService#uninstall", extension.identifier.id);
    return this.uninstallExtensions([{ extension, options }]);
  }
  async toggleAppliationScope(extension, fromProfileLocation) {
    if ($Pn(extension.manifest) || extension.isBuiltin) {
      return extension;
    }
    if (extension.isApplicationScoped) {
      let local = await this.updateMetadata(extension, { isApplicationScoped: false }, this.H.defaultProfile.extensionsResource);
      if (!this.D.extUri.isEqual(fromProfileLocation, this.H.defaultProfile.extensionsResource)) {
        local = await this.$(extension, this.H.defaultProfile.extensionsResource, fromProfileLocation);
      }
      for (const profile of this.H.profiles) {
        const existing = (await this.getInstalled(1, profile.extensionsResource)).find((e) => $8p(e.identifier, extension.identifier));
        if (existing) {
          this.w.fire({ local: existing, profileLocation: profile.extensionsResource });
        } else {
          this.u.fire({ identifier: extension.identifier, profileLocation: profile.extensionsResource });
        }
      }
      return local;
    } else {
      const local = this.D.extUri.isEqual(fromProfileLocation, this.H.defaultProfile.extensionsResource) ? await this.updateMetadata(extension, { isApplicationScoped: true }, this.H.defaultProfile.extensionsResource) : await this.$(extension, fromProfileLocation, this.H.defaultProfile.extensionsResource, { isApplicationScoped: true });
      this.s.fire([{ identifier: local.identifier, operation: 2, local, profileLocation: this.H.defaultProfile.extensionsResource, applicationScoped: true }]);
      return local;
    }
  }
  getExtensionsControlManifest() {
    const now = (/* @__PURE__ */ new Date()).getTime();
    if (!this.g || now - this.h > 1e3 * 60 * 5) {
      this.g = this.W();
      this.h = now;
    }
    return this.g;
  }
  registerParticipant(participant) {
    this.y.push(participant);
  }
  async resetPinnedStateForAllUserExtensions(pinned) {
    try {
      await this.M(this.H.profiles.map(async (profile) => {
        const extensions = await this.getInstalled(1, profile.extensionsResource);
        await this.M(extensions.map(async (extension) => {
          if (extension.pinned !== pinned) {
            await this.updateMetadata(extension, { pinned }, profile.extensionsResource);
          }
        }));
      }));
    } catch (error) {
      this.F.error("Error while resetting pinned state for all user extensions", $kb(error));
      throw error;
    }
  }
  async I(extensions) {
    const installExtensionResultsMap = /* @__PURE__ */ new Map();
    const installingExtensionsMap = /* @__PURE__ */ new Map();
    const alreadyRequestedInstallations = [];
    const getInstallExtensionTaskKey = (extension, profileLocation) => `${$9p.create(extension).toString()}-${profileLocation.toString()}`;
    const createInstallExtensionTask = (manifest, extension, options, root) => {
      if (!URI.isUri(extension)) {
        if (installingExtensionsMap.has(`${extension.identifier.id.toLowerCase()}-${options.profileLocation.toString()}`)) {
          return;
        }
        const existingInstallingExtension = this.j.get(getInstallExtensionTaskKey(extension, options.profileLocation));
        if (existingInstallingExtension) {
          if (root && this.L(root, existingInstallingExtension.task)) {
            const identifier = existingInstallingExtension.task.identifier;
            this.F.info("Waiting for already requested installing extension", identifier.id, root.identifier.id, options.profileLocation.toString());
            existingInstallingExtension.waitingTasks.push(root);
            alreadyRequestedInstallations.push(Event.toPromise(Event.filter(this.onDidInstallExtensions, (results) => results.some((result) => $8p(result.identifier, identifier)))).then((results) => {
              this.F.info("Finished waiting for already requested installing extension", identifier.id, root.identifier.id, options.profileLocation.toString());
              const result = results.find((result2) => $8p(result2.identifier, identifier));
              if (!result?.local) {
                throw new Error(`Extension ${identifier.id} is not installed`);
              }
            }));
          }
          return;
        }
      }
      const installExtensionTask = this.Y(manifest, extension, options);
      const key = `${$aq(manifest.publisher, manifest.name)}-${options.profileLocation.toString()}`;
      installingExtensionsMap.set(key, { task: installExtensionTask, root });
      this.n.fire({ identifier: installExtensionTask.identifier, source: extension, profileLocation: options.profileLocation });
      this.F.info("Installing extension:", installExtensionTask.identifier.id, options);
      if (!URI.isUri(extension)) {
        this.j.set(getInstallExtensionTaskKey(extension, options.profileLocation), { task: installExtensionTask, waitingTasks: [] });
      }
    };
    try {
      for (const { manifest, extension, options } of extensions) {
        const isApplicationScoped = options.isApplicationScoped || options.isBuiltin || $Pn(manifest);
        const installExtensionTaskOptions = {
          ...options,
          installOnlyNewlyAddedFromExtensionPack: options.installOnlyNewlyAddedFromExtensionPack ?? !URI.isUri(extension),
          isApplicationScoped,
          profileLocation: isApplicationScoped ? this.H.defaultProfile.extensionsResource : options.profileLocation ?? this.X(),
          productVersion: options.productVersion ?? { version: this.G.version, date: this.G.date }
        };
        const existingInstallExtensionTask = !URI.isUri(extension) ? this.j.get(getInstallExtensionTaskKey(extension, installExtensionTaskOptions.profileLocation)) : void 0;
        if (existingInstallExtensionTask) {
          this.F.info("Extension is already requested to install", existingInstallExtensionTask.task.identifier.id, installExtensionTaskOptions.profileLocation.toString());
          alreadyRequestedInstallations.push(existingInstallExtensionTask.task.waitUntilTaskIsFinished());
        } else {
          createInstallExtensionTask(manifest, extension, installExtensionTaskOptions, void 0);
        }
      }
      await Promise.all([...installingExtensionsMap.values()].map(async ({ task }) => {
        if (task.options.donotIncludePackAndDependencies) {
          this.F.info("Installing the extension without checking dependencies and pack", task.identifier.id);
        } else {
          try {
            const allDepsAndPackExtensionsToInstall = await this.N(task.identifier, task.manifest, !!task.options.installOnlyNewlyAddedFromExtensionPack, !!task.options.installPreReleaseVersion, task.options.profileLocation, task.options.productVersion);
            const installed = await this.getInstalled(void 0, task.options.profileLocation, task.options.productVersion);
            const options = { ...task.options, context: { ...task.options.context, [$yp]: true } };
            for (const { gallery, manifest } of $Zb(allDepsAndPackExtensionsToInstall, ({ gallery: gallery2 }) => gallery2.identifier.id)) {
              if (installed.some(({ identifier }) => $8p(identifier, gallery.identifier))) {
                continue;
              }
              createInstallExtensionTask(manifest, gallery, options, task);
            }
          } catch (error) {
            if (URI.isUri(task.source)) {
              if ($Yb(task.manifest.extensionDependencies)) {
                this.F.warn(`Cannot install dependencies of extension:`, task.identifier.id, error.message);
              }
              if ($Yb(task.manifest.extensionPack)) {
                this.F.warn(`Cannot install packed extensions of extension:`, task.identifier.id, error.message);
              }
            } else {
              this.F.error("Error while preparing to install dependencies and extension packs of the extension:", task.identifier.id);
              throw error;
            }
          }
        }
      }));
      const otherProfilesToUpdate = await this.J([...installingExtensionsMap.values()].map(({ task }) => task));
      for (const [profileLocation, task] of otherProfilesToUpdate) {
        createInstallExtensionTask(task.manifest, task.source, { ...task.options, profileLocation }, void 0);
      }
      await this.M([...installingExtensionsMap.entries()].map(async ([key, { task }]) => {
        const startTime = (/* @__PURE__ */ new Date()).getTime();
        let local;
        try {
          local = await task.run();
          await this.M(
            this.y.map((participant) => participant.postInstall(local, task.source, task.options, CancellationToken.None)),
            "PostInstall"
            /* ExtensionManagementErrorCode.PostInstall */
          );
        } catch (e) {
          const error = $3q(e);
          if (!URI.isUri(task.source)) {
            reportTelemetry(this.C, task.operation === 3 ? "extensionGallery:update" : "extensionGallery:install", {
              extensionData: $dq(task.source),
              error,
              source: task.options.context?.[$xp]
            });
          }
          installExtensionResultsMap.set(key, { error, identifier: task.identifier, operation: task.operation, source: task.source, context: task.options.context, profileLocation: task.options.profileLocation, applicationScoped: task.options.isApplicationScoped });
          this.F.error("Error while installing the extension", task.identifier.id, $kb(error), task.options.profileLocation.toString());
          throw error;
        }
        if (!URI.isUri(task.source)) {
          const isUpdate = task.operation === 3;
          const durationSinceUpdate = isUpdate ? void 0 : ((/* @__PURE__ */ new Date()).getTime() - task.source.lastUpdated) / 1e3;
          reportTelemetry(this.C, isUpdate ? "extensionGallery:update" : "extensionGallery:install", {
            extensionData: $dq(task.source),
            verificationStatus: task.verificationStatus,
            duration: (/* @__PURE__ */ new Date()).getTime() - startTime,
            durationSinceUpdate,
            source: task.options.context?.[$xp]
          });
          if ($r && task.operation !== 3) {
            try {
              await this.z.reportStatistic(
                local.manifest.publisher,
                local.manifest.name,
                local.manifest.version,
                "install"
                /* StatisticType.Install */
              );
            } catch (error) {
            }
          }
        }
        installExtensionResultsMap.set(key, { local, identifier: task.identifier, operation: task.operation, source: task.source, context: task.options.context, profileLocation: task.options.profileLocation, applicationScoped: local.isApplicationScoped });
      }));
      if (alreadyRequestedInstallations.length) {
        await this.M(alreadyRequestedInstallations);
      }
      return [...installExtensionResultsMap.values()];
    } catch (error) {
      const getAllDepsAndPacks = (extension, profileLocation, allDepsOrPacks) => {
        const depsOrPacks = [];
        if (extension.manifest.extensionDependencies?.length) {
          depsOrPacks.push(...extension.manifest.extensionDependencies);
        }
        if (extension.manifest.extensionPack?.length) {
          depsOrPacks.push(...extension.manifest.extensionPack);
        }
        for (const id2 of depsOrPacks) {
          if (allDepsOrPacks.includes(id2.toLowerCase())) {
            continue;
          }
          allDepsOrPacks.push(id2.toLowerCase());
          const installed = installExtensionResultsMap.get(`${id2.toLowerCase()}-${profileLocation.toString()}`);
          if (installed?.local) {
            allDepsOrPacks = getAllDepsAndPacks(installed.local, profileLocation, allDepsOrPacks);
          }
        }
        return allDepsOrPacks;
      };
      const getErrorResult = (task) => ({ identifier: task.identifier, operation: 2, source: task.source, context: task.options.context, profileLocation: task.options.profileLocation, error });
      const rollbackTasks = [];
      for (const [key, { task, root }] of installingExtensionsMap) {
        const result = installExtensionResultsMap.get(key);
        if (!result) {
          task.cancel();
          installExtensionResultsMap.set(key, getErrorResult(task));
        } else if (result.local && root && !installExtensionResultsMap.get(`${root.identifier.id.toLowerCase()}-${task.options.profileLocation.toString()}`)?.local) {
          rollbackTasks.push(this.Z(result.local, { versionOnly: true, profileLocation: task.options.profileLocation }));
          installExtensionResultsMap.set(key, getErrorResult(task));
        }
      }
      for (const [key, { task }] of installingExtensionsMap) {
        const result = installExtensionResultsMap.get(key);
        if (!result?.local) {
          continue;
        }
        if (task.options.donotIncludePackAndDependencies) {
          continue;
        }
        const depsOrPacks = getAllDepsAndPacks(result.local, task.options.profileLocation, [result.local.identifier.id.toLowerCase()]).slice(1);
        if (depsOrPacks.some((depOrPack) => installingExtensionsMap.has(`${depOrPack.toLowerCase()}-${task.options.profileLocation.toString()}`) && !installExtensionResultsMap.get(`${depOrPack.toLowerCase()}-${task.options.profileLocation.toString()}`)?.local)) {
          rollbackTasks.push(this.Z(result.local, { versionOnly: true, profileLocation: task.options.profileLocation }));
          installExtensionResultsMap.set(key, getErrorResult(task));
        }
      }
      if (rollbackTasks.length) {
        await Promise.allSettled(rollbackTasks.map(async (rollbackTask) => {
          try {
            await rollbackTask.run();
            this.F.info("Rollback: Uninstalled extension", rollbackTask.extension.identifier.id);
          } catch (error2) {
            this.F.warn("Rollback: Error while uninstalling extension", rollbackTask.extension.identifier.id, $kb(error2));
          }
        }));
      }
      throw error;
    } finally {
      for (const { task } of installingExtensionsMap.values()) {
        if (task.source && !URI.isUri(task.source)) {
          this.j.delete(getInstallExtensionTaskKey(task.source, task.options.profileLocation));
        }
      }
      if (installExtensionResultsMap.size) {
        const results = [...installExtensionResultsMap.values()];
        for (const result of results) {
          if (result.local) {
            this.F.info(`Extension installed successfully:`, result.identifier.id, result.profileLocation.toString());
          }
        }
        this.s.fire(results);
      }
    }
  }
  async J(tasks) {
    const otherProfilesToUpdate = [];
    const profileExtensionsCache = new $Mc();
    for (const task of tasks) {
      if (task.operation !== 3 || task.options.isApplicationScoped || task.options.pinned || task.options.installGivenVersion || URI.isUri(task.source)) {
        continue;
      }
      for (const profile of this.H.profiles) {
        if (this.D.extUri.isEqual(profile.extensionsResource, task.options.profileLocation)) {
          continue;
        }
        let installedExtensions = profileExtensionsCache.get(profile.extensionsResource);
        if (!installedExtensions) {
          installedExtensions = await this.getInstalled(1, profile.extensionsResource);
          profileExtensionsCache.set(profile.extensionsResource, installedExtensions);
        }
        const installedExtension = installedExtensions.find((e) => $8p(e.identifier, task.identifier));
        if (installedExtension && !installedExtension.pinned) {
          otherProfilesToUpdate.push([profile.extensionsResource, task]);
        }
      }
    }
    return otherProfilesToUpdate;
  }
  L(taskToWait, taskToWaitFor) {
    for (const [, { task, waitingTasks }] of this.j.entries()) {
      if (task === taskToWait) {
        if (waitingTasks.includes(taskToWaitFor)) {
          return false;
        }
        if (waitingTasks.some((waitingTask) => this.L(waitingTask, taskToWaitFor))) {
          return false;
        }
      }
      if (task === taskToWaitFor && waitingTasks[0] && !this.L(taskToWait, waitingTasks[0])) {
        return false;
      }
    }
    return true;
  }
  async M(promises12, errorCode) {
    const results = [];
    const errors = [];
    const promiseResults = await Promise.allSettled(promises12);
    for (const r of promiseResults) {
      if (r.status === "fulfilled") {
        results.push(r.value);
      } else {
        errors.push($3q(r.reason, errorCode));
      }
    }
    if (!errors.length) {
      return results;
    }
    if (errors.length === 1) {
      throw errors[0];
    }
    let error = new $Ip(
      "",
      "Unknown"
      /* ExtensionManagementErrorCode.Unknown */
    );
    for (const current of errors) {
      error = new $Ip(error.message ? `${error.message}, ${current.message}` : current.message, current.code !== "Unknown" && current.code !== "Internal" ? current.code : error.code);
    }
    throw error;
  }
  async N(extensionIdentifier, manifest, getOnlyNewlyAddedFromExtensionPack, installPreRelease, profile, productVersion) {
    if (!this.z.isEnabled()) {
      return [];
    }
    const installed = await this.getInstalled(void 0, profile, productVersion);
    const knownIdentifiers = [];
    const allDependenciesAndPacks = [];
    const collectDependenciesAndPackExtensionsToInstall = async (extensionIdentifier2, manifest2) => {
      knownIdentifiers.push(extensionIdentifier2);
      const dependecies = manifest2.extensionDependencies || [];
      const dependenciesAndPackExtensions = [...dependecies];
      if (manifest2.extensionPack) {
        const existing = getOnlyNewlyAddedFromExtensionPack ? installed.find((e) => $8p(e.identifier, extensionIdentifier2)) : void 0;
        for (const extension of manifest2.extensionPack) {
          if (!(existing && existing.manifest.extensionPack && existing.manifest.extensionPack.some((old) => $8p({ id: old }, { id: extension })))) {
            if (dependenciesAndPackExtensions.every((e) => !$8p({ id: e }, { id: extension }))) {
              dependenciesAndPackExtensions.push(extension);
            }
          }
        }
      }
      if (dependenciesAndPackExtensions.length) {
        const ids = dependenciesAndPackExtensions.filter((id2) => knownIdentifiers.every((galleryIdentifier) => !$8p(galleryIdentifier, { id: id2 })));
        if (ids.length) {
          const galleryExtensions = await this.z.getExtensions(ids.map((id2) => ({ id: id2, preRelease: installPreRelease })), CancellationToken.None);
          for (const galleryExtension of galleryExtensions) {
            if (knownIdentifiers.find((identifier) => $8p(identifier, galleryExtension.identifier))) {
              continue;
            }
            const isDependency = dependecies.some((id2) => $8p({ id: id2 }, galleryExtension.identifier));
            let compatible;
            try {
              compatible = await this.O(galleryExtension, false, installPreRelease, productVersion);
            } catch (error) {
              if (!isDependency) {
                this.F.info("Skipping the packed extension as it cannot be installed", galleryExtension.identifier.id, $kb(error));
                continue;
              } else {
                throw error;
              }
            }
            allDependenciesAndPacks.push({ gallery: compatible.extension, manifest: compatible.manifest });
            await collectDependenciesAndPackExtensionsToInstall(compatible.extension.identifier, compatible.manifest);
          }
        }
      }
    };
    await collectDependenciesAndPackExtensionsToInstall(extensionIdentifier, manifest);
    return allDependenciesAndPacks;
  }
  async O(extension, sameVersion, installPreRelease, productVersion) {
    let compatibleExtension;
    const extensionsControlManifest = await this.getExtensionsControlManifest();
    if (extensionsControlManifest.malicious.some((identifier) => $8p(extension.identifier, identifier))) {
      throw new $Ip(
        localize(1778, null, extension.identifier.id),
        "Malicious"
        /* ExtensionManagementErrorCode.Malicious */
      );
    }
    const deprecationInfo = extensionsControlManifest.deprecated[extension.identifier.id.toLowerCase()];
    if (deprecationInfo?.extension?.autoMigrate) {
      this.F.info(`The '${extension.identifier.id}' extension is deprecated, fetching the compatible '${deprecationInfo.extension.id}' extension instead.`);
      compatibleExtension = (await this.z.getExtensions([{ id: deprecationInfo.extension.id, preRelease: deprecationInfo.extension.preRelease }], { targetPlatform: await this.getTargetPlatform(), compatible: true, productVersion }, CancellationToken.None))[0];
      if (!compatibleExtension) {
        throw new $Ip(
          localize(1779, null, extension.identifier.id, deprecationInfo.extension.id),
          "Deprecated"
          /* ExtensionManagementErrorCode.Deprecated */
        );
      }
    } else {
      if (!await this.canInstall(extension)) {
        const targetPlatform = await this.getTargetPlatform();
        throw new $Ip(
          localize(1780, null, extension.identifier.id, this.G.nameLong, $Ap(targetPlatform)),
          "IncompatibleTargetPlatform"
          /* ExtensionManagementErrorCode.IncompatibleTargetPlatform */
        );
      }
      compatibleExtension = await this.P(extension, sameVersion, installPreRelease, productVersion);
      if (!compatibleExtension) {
        const incompatibleApiProposalsMessages = [];
        if (!$pq(extension.properties.enabledApiProposals ?? [], incompatibleApiProposalsMessages)) {
          throw new $Ip(
            localize(1781, null, extension.displayName ?? extension.identifier.id, incompatibleApiProposalsMessages[0]),
            "IncompatibleApi"
            /* ExtensionManagementErrorCode.IncompatibleApi */
          );
        }
        if (!installPreRelease && extension.properties.isPreReleaseVersion && (await this.z.getExtensions([extension.identifier], CancellationToken.None))[0]) {
          throw new $Ip(
            localize(1782, null, extension.displayName ?? extension.identifier.id),
            "ReleaseVersionNotFound"
            /* ExtensionManagementErrorCode.ReleaseVersionNotFound */
          );
        }
        throw new $Ip(
          localize(1783, null, extension.identifier.id, this.G.nameLong, this.G.version),
          "Incompatible"
          /* ExtensionManagementErrorCode.Incompatible */
        );
      }
    }
    this.F.info("Getting Manifest...", compatibleExtension.identifier.id);
    const manifest = await this.z.getManifest(compatibleExtension, CancellationToken.None);
    if (manifest === null) {
      throw new $Ip(
        `Missing manifest for extension ${compatibleExtension.identifier.id}`,
        "Invalid"
        /* ExtensionManagementErrorCode.Invalid */
      );
    }
    if (manifest.version !== compatibleExtension.version) {
      throw new $Ip(
        `Cannot install '${compatibleExtension.identifier.id}' extension because of version mismatch in Marketplace`,
        "Invalid"
        /* ExtensionManagementErrorCode.Invalid */
      );
    }
    return { extension: compatibleExtension, manifest };
  }
  async P(extension, sameVersion, includePreRelease, productVersion) {
    const targetPlatform = await this.getTargetPlatform();
    let compatibleExtension = null;
    if (!sameVersion && extension.hasPreReleaseVersion && extension.properties.isPreReleaseVersion !== includePreRelease) {
      compatibleExtension = (await this.z.getExtensions([{ ...extension.identifier, preRelease: includePreRelease }], { targetPlatform, compatible: true, productVersion }, CancellationToken.None))[0] || null;
    }
    if (!compatibleExtension && await this.z.isExtensionCompatible(extension, includePreRelease, targetPlatform, productVersion)) {
      compatibleExtension = extension;
    }
    if (!compatibleExtension) {
      if (sameVersion) {
        compatibleExtension = (await this.z.getExtensions([{ ...extension.identifier, version: extension.version }], { targetPlatform, compatible: true, productVersion }, CancellationToken.None))[0] || null;
      } else {
        compatibleExtension = await this.z.getCompatibleExtension(extension, includePreRelease, targetPlatform, productVersion);
      }
    }
    return compatibleExtension;
  }
  async uninstallExtensions(extensions) {
    const getUninstallExtensionTaskKey = (extension, uninstallOptions) => `${extension.identifier.id.toLowerCase()}${uninstallOptions.versionOnly ? `-${extension.manifest.version}` : ""}@${uninstallOptions.profileLocation.toString()}`;
    const createUninstallExtensionTask = (extension, uninstallOptions) => {
      const uninstallExtensionTask = this.Z(extension, uninstallOptions);
      this.m.set(getUninstallExtensionTaskKey(uninstallExtensionTask.extension, uninstallOptions), uninstallExtensionTask);
      this.F.info("Uninstalling extension from the profile:", `${extension.identifier.id}@${extension.manifest.version}`, uninstallOptions.profileLocation.toString());
      this.t.fire({ identifier: extension.identifier, profileLocation: uninstallOptions.profileLocation, applicationScoped: extension.isApplicationScoped });
      return uninstallExtensionTask;
    };
    const postUninstallExtension = (extension, uninstallOptions, error) => {
      if (error) {
        this.F.error("Failed to uninstall extension from the profile:", `${extension.identifier.id}@${extension.manifest.version}`, uninstallOptions.profileLocation.toString(), error.message);
      } else {
        this.F.info("Successfully uninstalled extension from the profile", `${extension.identifier.id}@${extension.manifest.version}`, uninstallOptions.profileLocation.toString());
      }
      reportTelemetry(this.C, "extensionGallery:uninstall", { extensionData: $cq(extension), error });
      this.u.fire({ identifier: extension.identifier, error: error?.code, profileLocation: uninstallOptions.profileLocation, applicationScoped: extension.isApplicationScoped });
    };
    const allTasks = [];
    const processedTasks = [];
    const alreadyRequestedUninstalls = [];
    const installedExtensionsMap = new $Mc();
    for (const { extension, options } of extensions) {
      const uninstallOptions = {
        ...options,
        profileLocation: extension.isApplicationScoped ? this.H.defaultProfile.extensionsResource : options?.profileLocation ?? this.X()
      };
      const uninstallExtensionTask = this.m.get(getUninstallExtensionTaskKey(extension, uninstallOptions));
      if (uninstallExtensionTask) {
        this.F.info("Extensions is already requested to uninstall", extension.identifier.id);
        alreadyRequestedUninstalls.push(uninstallExtensionTask.waitUntilTaskIsFinished());
      } else {
        allTasks.push(createUninstallExtensionTask(extension, uninstallOptions));
      }
    }
    try {
      for (const task of allTasks.slice(0)) {
        let installed = installedExtensionsMap.get(task.options.profileLocation);
        if (!installed) {
          installedExtensionsMap.set(task.options.profileLocation, installed = await this.getInstalled(1, task.options.profileLocation));
        }
        if (task.options.donotIncludePack) {
          this.F.info("Uninstalling the extension without including packed extension", `${task.extension.identifier.id}@${task.extension.manifest.version}`);
        } else {
          const packedExtensions = this.S(task.extension, installed);
          for (const packedExtension of packedExtensions) {
            if (this.m.has(getUninstallExtensionTaskKey(packedExtension, task.options))) {
              this.F.info("Extensions is already requested to uninstall", packedExtension.identifier.id);
            } else {
              allTasks.push(createUninstallExtensionTask(packedExtension, task.options));
            }
          }
        }
        if (task.options.donotCheckDependents) {
          this.F.info("Uninstalling the extension without checking dependents", `${task.extension.identifier.id}@${task.extension.manifest.version}`);
        } else {
          this.Q(allTasks.map((task2) => task2.extension), installed, task.extension);
        }
      }
      await this.M(allTasks.map(async (task) => {
        try {
          await task.run();
          await this.M(this.y.map((participant) => participant.postUninstall(task.extension, task.options, CancellationToken.None)));
          if (task.extension.identifier.uuid) {
            try {
              await this.z.reportStatistic(
                task.extension.manifest.publisher,
                task.extension.manifest.name,
                task.extension.manifest.version,
                "uninstall"
                /* StatisticType.Uninstall */
              );
            } catch (error) {
            }
          }
        } catch (e) {
          const error = $3q(e);
          postUninstallExtension(task.extension, task.options, error);
          throw error;
        } finally {
          processedTasks.push(task);
        }
      }));
      if (alreadyRequestedUninstalls.length) {
        await this.M(alreadyRequestedUninstalls);
      }
      for (const task of allTasks) {
        postUninstallExtension(task.extension, task.options);
      }
    } catch (e) {
      const error = $3q(e);
      for (const task of allTasks) {
        try {
          task.cancel();
        } catch (error2) {
        }
        if (!processedTasks.includes(task)) {
          postUninstallExtension(task.extension, task.options, error);
        }
      }
      throw error;
    } finally {
      for (const task of allTasks) {
        if (!this.m.delete(getUninstallExtensionTaskKey(task.extension, task.options))) {
          this.F.warn("Uninstallation task is not found in the cache", task.extension.identifier.id);
        }
      }
    }
  }
  Q(extensionsToUninstall, installed, extensionToUninstall) {
    for (const extension of extensionsToUninstall) {
      const dependents = this.U(extension, installed);
      if (dependents.length) {
        const remainingDependents = dependents.filter((dependent) => !extensionsToUninstall.some((e) => $8p(e.identifier, dependent.identifier)));
        if (remainingDependents.length) {
          throw new Error(this.R(extension, remainingDependents, extensionToUninstall));
        }
      }
    }
  }
  R(dependingExtension, dependents, extensionToUninstall) {
    if (extensionToUninstall === dependingExtension) {
      if (dependents.length === 1) {
        return localize(1784, null, extensionToUninstall.manifest.displayName || extensionToUninstall.manifest.name, dependents[0].manifest.displayName || dependents[0].manifest.name);
      }
      if (dependents.length === 2) {
        return localize(1785, null, extensionToUninstall.manifest.displayName || extensionToUninstall.manifest.name, dependents[0].manifest.displayName || dependents[0].manifest.name, dependents[1].manifest.displayName || dependents[1].manifest.name);
      }
      return localize(1786, null, extensionToUninstall.manifest.displayName || extensionToUninstall.manifest.name, dependents[0].manifest.displayName || dependents[0].manifest.name, dependents[1].manifest.displayName || dependents[1].manifest.name);
    }
    if (dependents.length === 1) {
      return localize(1787, null, extensionToUninstall.manifest.displayName || extensionToUninstall.manifest.name, dependingExtension.manifest.displayName || dependingExtension.manifest.name, dependents[0].manifest.displayName || dependents[0].manifest.name);
    }
    if (dependents.length === 2) {
      return localize(1788, null, extensionToUninstall.manifest.displayName || extensionToUninstall.manifest.name, dependingExtension.manifest.displayName || dependingExtension.manifest.name, dependents[0].manifest.displayName || dependents[0].manifest.name, dependents[1].manifest.displayName || dependents[1].manifest.name);
    }
    return localize(1789, null, extensionToUninstall.manifest.displayName || extensionToUninstall.manifest.name, dependingExtension.manifest.displayName || dependingExtension.manifest.name, dependents[0].manifest.displayName || dependents[0].manifest.name, dependents[1].manifest.displayName || dependents[1].manifest.name);
  }
  S(extension, installed, checked = []) {
    if (checked.indexOf(extension) !== -1) {
      return [];
    }
    checked.push(extension);
    const extensionsPack = extension.manifest.extensionPack ? extension.manifest.extensionPack : [];
    if (extensionsPack.length) {
      const packedExtensions = installed.filter((i) => !i.isBuiltin && extensionsPack.some((id2) => $8p({ id: id2 }, i.identifier)));
      const packOfPackedExtensions = [];
      for (const packedExtension of packedExtensions) {
        packOfPackedExtensions.push(...this.S(packedExtension, installed, checked));
      }
      return [...packedExtensions, ...packOfPackedExtensions];
    }
    return [];
  }
  U(extension, installed) {
    return installed.filter((e) => e.manifest.extensionDependencies && e.manifest.extensionDependencies.some((id2) => $8p({ id: id2 }, extension.identifier)));
  }
  async W() {
    try {
      this.F.trace("ExtensionManagementService.updateControlCache");
      return await this.z.getExtensionsControlManifest();
    } catch (err) {
      this.F.trace("ExtensionManagementService.refreshControlCache - failed to get extension control manifest", $kb(err));
      return { malicious: [], deprecated: {}, search: [] };
    }
  }
};
$2q = __decorate([
  __param(0, $Gp),
  __param(1, $tm),
  __param(2, $5l),
  __param(3, $uk),
  __param(4, $Nk),
  __param(5, $7l)
], $2q);
function $3q(error, code) {
  if (error instanceof $Ip) {
    return error;
  }
  let extensionManagementError;
  if (error instanceof $Hp) {
    extensionManagementError = new $Ip(
      error.message,
      error.code === "DownloadFailedWriting" ? "DownloadFailedWriting" : "Gallery"
      /* ExtensionManagementErrorCode.Gallery */
    );
  } else {
    extensionManagementError = new $Ip(error.message, $eb(error) ? "Cancelled" : code ?? "Internal");
  }
  extensionManagementError.stack = error.stack;
  return extensionManagementError;
}
function reportTelemetry(telemetryService, eventName, { extensionData, verificationStatus, duration, error, source, durationSinceUpdate }) {
  telemetryService.publicLog(eventName, {
    ...extensionData,
    source,
    duration,
    durationSinceUpdate,
    success: !error,
    errorcode: error?.code,
    verificationStatus: verificationStatus === ExtensionSignatureVerificationCode.Success ? "Verified" : verificationStatus ?? "Unverified"
  });
}
var $4q = class {
  constructor() {
    this.d = new $Yh();
  }
  async waitUntilTaskIsFinished() {
    await this.d.wait();
    return this.g;
  }
  run() {
    if (!this.g) {
      this.g = $Mh((token) => this.h(token));
    }
    this.d.open();
    return this.g;
  }
  cancel() {
    if (!this.g) {
      this.g = $Mh((token) => {
        return new Promise((c, e) => {
          const disposable = token.onCancellationRequested(() => {
            disposable.dispose();
            e(new $fb());
          });
        });
      });
      this.d.open();
    }
    this.g.cancel();
  }
};

// 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, code) {
    super(message);
    this.code = code;
  }
};
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(path2) {
    return this.r.extUri.joinPath(this.j, path2);
  }
  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/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 promises12 = [];
    promises12.push(this.M(!!scanOptions.useCache, scanOptions.language));
    promises12.push(this.N(scanOptions.language, !!scanOptions.checkControlFile));
    const [defaultSystemExtensions, devSystemExtensions] = await Promise.all(promises12);
    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, type2, scanOptions, pickLatest) {
    if (!scanOptions.includeAllVersions) {
      extensions = this.L(type2 === 0 ? extensions : void 0, type2 === 1 ? extensions : void 0, type2 === "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, type2, 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, type2, 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, type2, 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 = type2;
    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 type2 = metadata?.isSystem ? 0 : input.type;
        const isBuiltin = type2 === 0 || !!metadata?.isBuiltin;
        manifest = await this.y(input.location, manifest, $_q.createNlsConfiguration(input));
        let extension = {
          type: type2,
          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/extensionManagementUtil.js
function $cr(e) {
  let errorCode = "Extract";
  if (e instanceof $Xq) {
    if (e.type === "CorruptZip") {
      errorCode = "CorruptZip";
    } else if (e.type === "Incomplete") {
      errorCode = "IncompleteZip";
    }
  }
  return $3q(e, errorCode);
}
async function $dr(vsixPath) {
  let data;
  try {
    data = await $1q(vsixPath, "extension/package.json");
  } catch (e) {
    throw $cr(e);
  }
  try {
    return JSON.parse(data.toString("utf8"));
  } catch (err) {
    throw new $Ip(
      localize(1845, null),
      "Invalid"
      /* ExtensionManagementErrorCode.Invalid */
    );
  }
}

// out-build/vs/platform/extensionManagement/node/extensionDownloader.js
var $er_1;
var $er = class $er2 extends $0c {
  static {
    $er_1 = this;
  }
  static {
    this.c = ".sigzip";
  }
  constructor(environmentService, h, j, m, n, r) {
    super();
    this.h = h;
    this.j = j;
    this.m = m;
    this.n = n;
    this.r = r;
    this.extensionsDownloadDir = environmentService.extensionsDownloadLocation;
    this.f = 20;
    this.g = this.C();
  }
  async download(extension, operation, verifySignature, clientTargetPlatform) {
    await this.g;
    const location = await this.t(extension, operation);
    if (!verifySignature || !extension.isSigned) {
      return { location, verificationStatus: void 0 };
    }
    let signatureArchiveLocation;
    try {
      signatureArchiveLocation = await this.u(extension);
      const verificationStatus = (await this.m.verify(extension.identifier.id, extension.version, location.fsPath, signatureArchiveLocation.fsPath, clientTargetPlatform))?.code;
      if (verificationStatus === ExtensionSignatureVerificationCode.PackageIsInvalidZip || verificationStatus === ExtensionSignatureVerificationCode.SignatureArchiveIsInvalidZip) {
        try {
          await this.delete(location);
        } catch (error) {
          this.r.error(error);
        }
        throw new $Ip(
          $Wq,
          "CorruptZip"
          /* ExtensionManagementErrorCode.CorruptZip */
        );
      }
      return { location, verificationStatus };
    } catch (error) {
      try {
        await this.delete(location);
      } catch (error2) {
        this.r.error(error2);
      }
      throw error;
    } finally {
      if (signatureArchiveLocation) {
        try {
          await this.delete(signatureArchiveLocation);
        } catch (error) {
          this.r.error(error);
        }
      }
    }
  }
  async t(extension, operation) {
    try {
      const location = $Ah(this.extensionsDownloadDir, this.D(extension));
      const attempts = await this.y(extension, "vsix", async () => {
        await this.w(extension, location, (location2) => this.j.download(extension, location2, operation));
        try {
          await this.z(location.fsPath, "extension/package.json");
        } catch (error) {
          try {
            await this.h.del(location);
          } catch (e) {
            this.r.warn(`Error while deleting: ${location.path}`, $kb(e));
          }
          throw error;
        }
      }, 2);
      if (attempts > 1) {
        this.n.publicLog2("extensiongallery:downloadvsix:retry", {
          extensionId: extension.identifier.id,
          attempts
        });
      }
      return location;
    } catch (e) {
      throw $3q(
        e,
        "Download"
        /* ExtensionManagementErrorCode.Download */
      );
    }
  }
  async u(extension) {
    try {
      const location = $Ah(this.extensionsDownloadDir, `.${$jh()}`);
      const attempts = await this.y(extension, "sigzip", async () => {
        await this.j.downloadSignatureArchive(extension, location);
        try {
          await this.z(location.fsPath, ".signature.p7s");
        } catch (error) {
          try {
            await this.h.del(location);
          } catch (e) {
            this.r.warn(`Error while deleting: ${location.path}`, $kb(e));
          }
          throw error;
        }
      }, 2);
      if (attempts > 1) {
        this.n.publicLog2("extensiongallery:downloadsigzip:retry", {
          extensionId: extension.identifier.id,
          attempts
        });
      }
      return location;
    } catch (e) {
      throw $3q(
        e,
        "DownloadSignature"
        /* ExtensionManagementErrorCode.DownloadSignature */
      );
    }
  }
  async w(extension, location, downloadFn) {
    if (await this.h.exists(location)) {
      return;
    }
    if (location.scheme !== Schemas.file) {
      await downloadFn(location);
      return;
    }
    const tempLocation = $Ah(this.extensionsDownloadDir, `.${$jh()}`);
    try {
      await downloadFn(tempLocation);
    } catch (error) {
      try {
        await this.h.del(tempLocation);
      } catch (e) {
      }
      throw error;
    }
    try {
      await Promises2.rename(
        tempLocation.fsPath,
        location.fsPath,
        2 * 60 * 1e3
        /* Retry for 2 minutes */
      );
    } catch (error) {
      try {
        await this.h.del(tempLocation);
      } catch (e) {
      }
      let exists = false;
      try {
        exists = await this.h.exists(location);
      } catch (e) {
      }
      if (exists) {
        this.r.info(`Rename failed because the file was downloaded by another source. So ignoring renaming.`, extension.identifier.id, location.path);
      } else {
        this.r.info(`Rename failed because of ${$kb(error)}. Deleted the file from downloaded location`, tempLocation.path);
        throw error;
      }
    }
  }
  async y(extension, name, downloadFn, retries) {
    let attempts = 1;
    while (true) {
      try {
        await downloadFn();
        return attempts;
      } catch (e) {
        if (attempts++ > retries) {
          throw e;
        }
        this.r.warn(`Failed downloading ${name}. ${$kb(e)}. Retry again...`, extension.identifier.id);
      }
    }
  }
  async z(zipPath, filePath) {
    try {
      await $1q(zipPath, filePath);
    } catch (e) {
      throw $cr(e);
    }
  }
  async delete(location) {
    await this.g;
    await this.h.del(location);
  }
  async C() {
    try {
      if (!await this.h.exists(this.extensionsDownloadDir)) {
        this.r.trace("Extension VSIX downloads cache dir does not exist");
        return;
      }
      const folderStat = await this.h.resolve(this.extensionsDownloadDir, { resolveMetadata: true });
      if (folderStat.children) {
        const toDelete = [];
        const vsixs = [];
        const signatureArchives = [];
        for (const stat of folderStat.children) {
          if (stat.name.endsWith($er_1.c)) {
            signatureArchives.push(stat.resource);
          } else {
            const extension = $9p.parse(stat.name);
            if (extension) {
              vsixs.push([extension, stat]);
            }
          }
        }
        const byExtension = $bq(vsixs, ([extension]) => extension);
        const distinct = [];
        for (const p of byExtension) {
          p.sort((a, b) => rcompare(a[0].version, b[0].version));
          toDelete.push(...p.slice(1).map((e) => e[1].resource));
          distinct.push(p[0][1]);
        }
        distinct.sort((a, b) => a.mtime - b.mtime);
        toDelete.push(...distinct.slice(0, Math.max(0, distinct.length - this.f)).map((s) => s.resource));
        toDelete.push(...signatureArchives);
        await Promises.settled(toDelete.map((resource) => {
          this.r.trace("Deleting from cache", resource.path);
          return this.h.del(resource);
        }));
      }
    } catch (e) {
      this.r.error(e);
    }
  }
  D(extension) {
    return this.f ? $9p.create(extension).toString().toLowerCase() : $jh();
  }
};
$er = $er_1 = __decorate([
  __param(0, $8i),
  __param(1, $ul),
  __param(2, $Gp),
  __param(3, $Qq),
  __param(4, $tm),
  __param(5, $uk)
], $er);

// out-build/vs/platform/extensionManagement/node/extensionLifecycle.js
import { fork } from "child_process";
var $fr = class $fr2 extends $0c {
  constructor(b, f) {
    super();
    this.b = b;
    this.f = f;
    this.a = new $6h(5);
  }
  async postUninstall(extension) {
    const script = this.g(extension, "uninstall");
    if (script) {
      this.f.info(extension.identifier.id, extension.manifest.version, `Running post uninstall script`);
      await this.a.queue(async () => {
        try {
          await this.h(script.script, "uninstall", script.args, true, extension);
          this.f.info(`Finished running post uninstall script`, extension.identifier.id, extension.manifest.version);
        } catch (error) {
          this.f.error("Failed to run post uninstall script", extension.identifier.id, extension.manifest.version);
          this.f.error(error);
        }
      });
    }
    try {
      await Promises2.rm(this.m(extension));
    } catch (error) {
      this.f.error("Error while removing extension storage path", extension.identifier.id);
      this.f.error(error);
    }
  }
  g(extension, type2) {
    const scriptKey = `vscode:${type2}`;
    if (extension.location.scheme === Schemas.file && extension.manifest && extension.manifest["scripts"] && typeof extension.manifest["scripts"][scriptKey] === "string") {
      const script = extension.manifest["scripts"][scriptKey].split(" ");
      if (script.length < 2 || script[0] !== "node" || !script[1]) {
        this.f.warn(extension.identifier.id, extension.manifest.version, `${scriptKey} should be a node script`);
        return null;
      }
      return { script: $vc(extension.location.fsPath, script[1]), args: script.slice(2) || [] };
    }
    return null;
  }
  h(lifecycleHook, lifecycleType, args, timeout, extension) {
    return new Promise((c, e) => {
      const extensionLifecycleProcess = this.j(lifecycleHook, lifecycleType, args, extension);
      let timeoutHandler;
      const onexit = (error) => {
        if (timeoutHandler) {
          clearTimeout(timeoutHandler);
          timeoutHandler = null;
        }
        if (error) {
          e(error);
        } else {
          c(void 0);
        }
      };
      extensionLifecycleProcess.on("error", (err) => {
        onexit($Kj(err) || "Unknown");
      });
      extensionLifecycleProcess.on("exit", (code, signal) => {
        onexit(code ? `post-${lifecycleType} process exited with code ${code}` : void 0);
      });
      if (timeout) {
        timeoutHandler = setTimeout(() => {
          timeoutHandler = null;
          extensionLifecycleProcess.kill();
          e("timed out");
        }, 5e3);
      }
    });
  }
  j(uninstallHook, lifecycleType, args, extension) {
    const opts = {
      silent: true,
      execArgv: void 0
    };
    const extensionUninstallProcess = fork(uninstallHook, [`--type=extension-post-${lifecycleType}`, ...args], opts);
    extensionUninstallProcess.stdout.setEncoding("utf8");
    extensionUninstallProcess.stderr.setEncoding("utf8");
    const onStdout = Event.fromNodeEventEmitter(extensionUninstallProcess.stdout, "data");
    const onStderr = Event.fromNodeEventEmitter(extensionUninstallProcess.stderr, "data");
    this.B(onStdout((data) => this.f.info(extension.identifier.id, extension.manifest.version, `post-${lifecycleType}`, data)));
    this.B(onStderr((data) => this.f.error(extension.identifier.id, extension.manifest.version, `post-${lifecycleType}`, data)));
    const onOutput = Event.any(Event.map(onStdout, (o) => ({ data: `%c${o}`, format: [""] }), this.q), Event.map(onStderr, (o) => ({ data: `%c${o}`, format: ["color: red"] }), this.q));
    const onDebouncedOutput = Event.debounce(onOutput, (r, o) => {
      return r ? { data: r.data + o.data, format: [...r.format, ...o.format] } : { data: o.data, format: o.format };
    }, 100, void 0, void 0, void 0, this.q);
    onDebouncedOutput((data) => {
      console.group(extension.identifier.id);
      console.log(data.data, ...data.format);
      console.groupEnd();
    });
    return extensionUninstallProcess;
  }
  m(extension) {
    return $vc(this.b.defaultProfile.globalStorageHome.fsPath, extension.identifier.id.toLowerCase());
  }
};
$fr = __decorate([
  __param(0, $7l),
  __param(1, $uk)
], $fr);

// out-build/vs/platform/extensionManagement/node/extensionsManifestCache.js
var $gr = class extends $0c {
  constructor(a, b, c, extensionsManagementService, f) {
    super();
    this.a = a;
    this.b = b;
    this.c = c;
    this.f = f;
    this.B(extensionsManagementService.onDidInstallExtensions((e) => this.g(e)));
    this.B(extensionsManagementService.onDidUninstallExtension((e) => this.h(e)));
  }
  g(results) {
    for (const r of results) {
      if (r.local) {
        this.invalidate(r.profileLocation);
      }
    }
  }
  h(e) {
    if (!e.error) {
      this.invalidate(e.profileLocation);
    }
  }
  async invalidate(extensionsManifestLocation) {
    if (extensionsManifestLocation) {
      for (const profile of this.a.profiles) {
        if (this.c.extUri.isEqual(profile.extensionsResource, extensionsManifestLocation)) {
          await this.j(profile);
        }
      }
    } else {
      await this.j(this.a.defaultProfile);
    }
  }
  async j(profile) {
    try {
      await this.b.del(this.c.extUri.joinPath(profile.cacheHome, $Gn));
    } catch (error) {
      if ($Ll(error) !== 1) {
        this.f.error(error);
      }
    }
  }
};

// out-build/vs/platform/extensionManagement/node/extensionsWatcher.js
var $hr = class extends $0c {
  constructor(f, g, h, j, m, n, r) {
    super();
    this.f = f;
    this.g = g;
    this.h = h;
    this.j = j;
    this.m = m;
    this.n = n;
    this.r = r;
    this.a = this.B(new $De());
    this.onDidChangeExtensionsByAnotherSource = this.a.event;
    this.b = /* @__PURE__ */ new Map();
    this.c = this.B(new $gd());
    this.s().then(null, (error) => r.error("Error while initializing Extensions Watcher", $kb(error)));
  }
  async s() {
    await this.g.initializeDefaultProfileExtensions();
    await this.u(this.h.profiles);
    this.t();
    await this.H();
  }
  t() {
    this.B(this.h.onDidChangeProfiles((e) => this.u(e.added)));
    this.B(this.j.onAddExtensions((e) => this.w(e)));
    this.B(this.j.onDidAddExtensions((e) => this.y(e)));
    this.B(this.j.onRemoveExtensions((e) => this.z(e)));
    this.B(this.j.onDidRemoveExtensions((e) => this.C(e)));
    this.B(this.n.onDidFilesChange((e) => this.D(e)));
  }
  async u(added) {
    try {
      if (added.length) {
        await Promise.all(added.map((profile) => {
          this.c.set(profile.id, $7c(
            this.n.watch(this.m.extUri.dirname(profile.extensionsResource)),
            // Also listen to the resource incase the resource is a symlink - https://github.com/microsoft/vscode/issues/118134
            this.n.watch(profile.extensionsResource)
          ));
          return this.G(profile.extensionsResource);
        }));
      }
    } catch (error) {
      this.r.error(error);
      throw error;
    }
  }
  async w(e) {
    for (const extension of e.extensions) {
      this.I(this.L(extension.identifier, extension.version), e.profileLocation);
    }
  }
  async y(e) {
    for (const extension of e.extensions) {
      const key = this.L(extension.identifier, extension.version);
      if (e.error) {
        this.J(key, e.profileLocation);
      } else {
        this.I(key, e.profileLocation);
      }
    }
  }
  async z(e) {
    for (const extension of e.extensions) {
      this.J(this.L(extension.identifier, extension.version), e.profileLocation);
    }
  }
  async C(e) {
    const extensionsToUninstall = [];
    const promises12 = [];
    for (const extension of e.extensions) {
      const key = this.L(extension.identifier, extension.version);
      if (e.error) {
        this.I(key, e.profileLocation);
      } else {
        this.J(key, e.profileLocation);
        if (!this.b.has(key)) {
          this.r.debug("Extension is removed from all profiles", extension.identifier.id, extension.version);
          promises12.push(this.f.scanInstalledExtensionAtLocation(extension.location).then((result) => {
            if (result) {
              extensionsToUninstall.push(result);
            } else {
              this.r.info("Extension not found at the location", extension.location.toString());
            }
          }, (error) => this.r.error(error)));
        }
      }
    }
    try {
      await Promise.all(promises12);
      if (extensionsToUninstall.length) {
        await this.H(extensionsToUninstall);
      }
    } catch (error) {
      this.r.error(error);
    }
  }
  D(e) {
    for (const profile of this.h.profiles) {
      if (e.contains(
        profile.extensionsResource,
        0,
        1
        /* FileChangeType.ADDED */
      )) {
        this.F(profile.extensionsResource);
      }
    }
  }
  async F(profileLocation) {
    const added = [], removed = [];
    const extensions = await this.j.scanProfileExtensions(profileLocation);
    const extensionKeys = /* @__PURE__ */ new Set();
    const cached = /* @__PURE__ */ new Set();
    for (const [key, profiles] of this.b) {
      if (profiles.has(profileLocation)) {
        cached.add(key);
      }
    }
    for (const extension of extensions) {
      const key = this.L(extension.identifier, extension.version);
      extensionKeys.add(key);
      if (!cached.has(key)) {
        added.push(extension.identifier);
        this.I(key, profileLocation);
      }
    }
    for (const key of cached) {
      if (!extensionKeys.has(key)) {
        const extension = this.M(key);
        if (extension) {
          removed.push(extension.identifier);
          this.J(key, profileLocation);
        }
      }
    }
    if (added.length || removed.length) {
      this.a.fire({ added: added.length ? { extensions: added, profileLocation } : void 0, removed: removed.length ? { extensions: removed, profileLocation } : void 0 });
    }
  }
  async G(extensionsProfileLocation) {
    const extensions = await this.j.scanProfileExtensions(extensionsProfileLocation);
    for (const extension of extensions) {
      this.I(this.L(extension.identifier, extension.version), extensionsProfileLocation);
    }
  }
  async H(toUninstall) {
    if (!toUninstall) {
      const installed = await this.f.scanAllUserInstalledExtensions();
      toUninstall = installed.filter((installedExtension) => !this.b.has(this.L(installedExtension.identifier, installedExtension.manifest.version)));
    }
    if (toUninstall.length) {
      await this.f.markAsUninstalled(...toUninstall);
    }
  }
  I(key, extensionsProfileLocation) {
    let profiles = this.b.get(key);
    if (!profiles) {
      this.b.set(key, profiles = new $Nc((uri) => this.m.extUri.getComparisonKey(uri)));
    }
    profiles.add(extensionsProfileLocation);
  }
  J(key, profileLocation) {
    const profiles = this.b.get(key);
    if (profiles) {
      profiles.delete(profileLocation);
    }
    if (!profiles?.size) {
      this.b.delete(key);
    }
  }
  L(identifier, version) {
    return `${$Mn.toKey(identifier.id)}@${version}`;
  }
  M(key) {
    const [id2, version] = $0p(key);
    return version ? { identifier: { id: id2 }, version } : void 0;
  }
};

// out-build/vs/platform/extensionManagement/node/extensionManagementService.js
var $ir = $1i($Jp);
var DELETED_FOLDER_POSTFIX = ".vsctmp";
var $jr = class $jr2 extends $2q {
  constructor(galleryService, telemetryService, logService, eb, fb, gb, hb, ib, jb, kb, productService, uriIdentityService, userDataProfilesService) {
    super(galleryService, telemetryService, uriIdentityService, logService, productService, userDataProfilesService);
    this.eb = eb;
    this.fb = fb;
    this.gb = gb;
    this.hb = hb;
    this.ib = ib;
    this.jb = jb;
    this.kb = kb;
    this.db = /* @__PURE__ */ new Map();
    this.wb = new $Nc();
    const extensionLifecycle = this.B(ib.createInstance($fr));
    this.ab = this.B(ib.createInstance($kr, (extension) => extensionLifecycle.postUninstall(extension)));
    this.bb = this.B(new $gr(userDataProfilesService, jb, uriIdentityService, this, this.F));
    this.cb = this.B(ib.createInstance($er));
    const extensionsWatcher = this.B(new $hr(this, this.fb, userDataProfilesService, gb, uriIdentityService, jb, logService));
    this.B(extensionsWatcher.onDidChangeExtensionsByAnotherSource((e) => this.vb(e)));
    this.xb();
  }
  getTargetPlatform() {
    if (!this.lb) {
      this.lb = $gq(this.jb, this.F);
    }
    return this.lb;
  }
  async zip(extension) {
    this.F.trace("ExtensionManagementService#zip", extension.identifier.id);
    const files = await this.ub(extension);
    const location = await zip($Ah(this.cb.extensionsDownloadDir, $jh()).fsPath, files);
    return URI.file(location);
  }
  async getManifest(vsix) {
    const { location, cleanup } = await this.nb(vsix);
    const zipPath = $wc(location.fsPath);
    try {
      return await $dr(zipPath);
    } finally {
      await cleanup();
    }
  }
  getInstalled(type2, profileLocation = this.H.defaultProfile.extensionsResource, productVersion = { version: this.G.version, date: this.G.date }) {
    return this.ab.scanExtensions(type2 ?? null, profileLocation, productVersion);
  }
  scanAllUserInstalledExtensions() {
    return this.ab.scanAllUserExtensions(false);
  }
  scanInstalledExtensionAtLocation(location) {
    return this.ab.scanUserExtensionAtLocation(location);
  }
  async install(vsix, options = {}) {
    this.F.trace("ExtensionManagementService#install", vsix.toString());
    const { location, cleanup } = await this.nb(vsix);
    try {
      const manifest = await $dr($wc(location.fsPath));
      const extensionId = $aq(manifest.publisher, manifest.name);
      if (manifest.engines && manifest.engines.vscode && !$oq(manifest.engines.vscode, this.G.version, this.G.date)) {
        throw new Error(localize(1832, null, extensionId, this.G.version));
      }
      const results = await this.I([{ manifest, extension: location, options }]);
      const result = results.find(({ identifier }) => $8p(identifier, { id: extensionId }));
      if (result?.local) {
        return result.local;
      }
      if (result?.error) {
        throw result.error;
      }
      throw $3q(new Error(`Unknown error while installing extension ${extensionId}`));
    } finally {
      await cleanup();
    }
  }
  async installFromLocation(location, profileLocation) {
    this.F.trace("ExtensionManagementService#installFromLocation", location.toString());
    const local = await this.ab.scanUserExtensionAtLocation(location);
    if (!local || !local.manifest.name || !local.manifest.version) {
      throw new Error(`Cannot find a valid extension from the location ${location.toString()}`);
    }
    await this.zb([[local, { source: "resource" }]], profileLocation);
    this.F.info("Successfully installed extension", local.identifier.id, profileLocation.toString());
    return local;
  }
  async installExtensionsFromProfile(extensions, fromProfileLocation, toProfileLocation) {
    this.F.trace("ExtensionManagementService#installExtensionsFromProfile", extensions, fromProfileLocation.toString(), toProfileLocation.toString());
    const extensionsToInstall = (await this.getInstalled(1, fromProfileLocation)).filter((e) => extensions.some((id2) => $8p(id2, e.identifier)));
    if (extensionsToInstall.length) {
      const metadata = await Promise.all(extensionsToInstall.map((e) => this.ab.scanMetadata(e, fromProfileLocation)));
      await this.zb(extensionsToInstall.map((e, index) => [e, metadata[index]]), toProfileLocation);
      this.F.info("Successfully installed extensions", extensionsToInstall.map((e) => e.identifier.id), toProfileLocation.toString());
    }
    return extensionsToInstall;
  }
  async updateMetadata(local, metadata, profileLocation) {
    this.F.trace("ExtensionManagementService#updateMetadata", local.identifier.id);
    if (metadata.isPreReleaseVersion) {
      metadata.preRelease = true;
      metadata.hasPreReleaseVersion = true;
    }
    if (metadata.isMachineScoped === false) {
      metadata.isMachineScoped = void 0;
    }
    if (metadata.isBuiltin === false) {
      metadata.isBuiltin = void 0;
    }
    if (metadata.pinned === false) {
      metadata.pinned = void 0;
    }
    local = await this.ab.updateMetadata(local, metadata, profileLocation);
    this.bb.invalidate(profileLocation);
    this.w.fire({ local, profileLocation });
    return local;
  }
  async reinstallFromGallery(extension) {
    this.F.trace("ExtensionManagementService#reinstallFromGallery", extension.identifier.id);
    if (!this.z.isEnabled()) {
      throw new Error(localize(1833, null));
    }
    const targetPlatform = await this.getTargetPlatform();
    const [galleryExtension] = await this.z.getExtensions([{ ...extension.identifier, preRelease: extension.preRelease }], { targetPlatform, compatible: true }, CancellationToken.None);
    if (!galleryExtension) {
      throw new Error(localize(1834, null));
    }
    await this.ab.setUninstalled(extension);
    try {
      await this.ab.removeUninstalledExtension(extension);
    } catch (e) {
      throw new Error(localize(1835, null, $Kj(e)));
    }
    return this.installFromGallery(galleryExtension);
  }
  $(extension, fromProfileLocation, toProfileLocation, metadata) {
    return this.ab.copyExtension(extension, fromProfileLocation, toProfileLocation, metadata);
  }
  copyExtensions(fromProfileLocation, toProfileLocation) {
    return this.ab.copyExtensions(fromProfileLocation, toProfileLocation, { version: this.G.version, date: this.G.date });
  }
  markAsUninstalled(...extensions) {
    return this.ab.setUninstalled(...extensions);
  }
  async cleanUp() {
    this.F.trace("ExtensionManagementService#cleanUp");
    try {
      await this.ab.cleanUp();
    } catch (error) {
      this.F.error(error);
    }
  }
  async download(extension, operation, donotVerifySignature) {
    const { location } = await this.sb(extension, operation, !donotVerifySignature);
    return location;
  }
  async nb(vsix) {
    if (vsix.scheme === Schemas.file) {
      return { location: vsix, async cleanup() {
      } };
    }
    this.F.trace("Downloading extension from", vsix.toString());
    const location = $Ah(this.cb.extensionsDownloadDir, $jh());
    await this.hb.download(vsix, location);
    this.F.info("Downloaded extension to", location.toString());
    const cleanup = async () => {
      try {
        await this.jb.del(location);
      } catch (error) {
        this.F.error(error);
      }
    };
    return { location, cleanup };
  }
  X() {
    return this.H.defaultProfile.extensionsResource;
  }
  Y(manifest, extension, options) {
    const extensionKey = extension instanceof URI ? new $9p({ id: $aq(manifest.publisher, manifest.name) }, manifest.version) : $9p.create(extension);
    return this.ib.createInstance(InstallExtensionInProfileTask, extensionKey, manifest, extension, options, (operation, token) => {
      if (extension instanceof URI) {
        return this.tb(extensionKey, extension, options, token);
      }
      let promise = this.db.get(extensionKey.toString());
      if (!promise) {
        this.db.set(extensionKey.toString(), promise = this.rb(extensionKey, extension, operation, options, token));
        promise.finally(() => this.db.delete(extensionKey.toString()));
      }
      return promise;
    }, this.ab);
  }
  Z(extension, options) {
    return new UninstallExtensionInProfileTask(extension, options, this.gb);
  }
  async rb(extensionKey, gallery, operation, options, token) {
    const { verificationStatus, location } = await this.sb(gallery, operation, !options.donotVerifySignature, options.context?.[$zp]);
    try {
      if (token.isCancellationRequested) {
        throw new $fb();
      }
      const manifest = await $dr(location.fsPath);
      if (!new $9p(gallery.identifier, gallery.version).equals(new $9p({ id: $aq(manifest.publisher, manifest.name) }, manifest.version))) {
        throw new $Ip(
          localize(1836, null, gallery.identifier.id),
          "Invalid"
          /* ExtensionManagementErrorCode.Invalid */
        );
      }
      const local = await this.ab.extractUserExtension(extensionKey, location.fsPath, {
        id: gallery.identifier.uuid,
        publisherId: gallery.publisherId,
        publisherDisplayName: gallery.publisherDisplayName,
        targetPlatform: gallery.properties.targetPlatform,
        isApplicationScoped: options.isApplicationScoped,
        isMachineScoped: options.isMachineScoped,
        isBuiltin: options.isBuiltin,
        isPreReleaseVersion: gallery.properties.isPreReleaseVersion,
        hasPreReleaseVersion: gallery.properties.isPreReleaseVersion,
        installedTimestamp: Date.now(),
        pinned: options.installGivenVersion ? true : !!options.pinned,
        preRelease: $Eg(options.preRelease) ? options.preRelease : options.installPreReleaseVersion || gallery.properties.isPreReleaseVersion,
        source: "gallery"
      }, false, token);
      return { local, verificationStatus };
    } catch (error) {
      try {
        await this.cb.delete(location);
      } catch (e) {
        this.F.warn(`Error while deleting the downloaded file`, location.toString(), $kb(e));
      }
      throw $3q(error);
    }
  }
  async sb(extension, operation, verifySignature, clientTargetPlatform) {
    if (verifySignature) {
      const value = this.kb.getValue("extensions.verifySignature");
      verifySignature = $Eg(value) ? value : true;
    }
    const { location, verificationStatus } = await this.cb.download(extension, operation, verifySignature, clientTargetPlatform);
    if (verificationStatus !== ExtensionSignatureVerificationCode.Success && verifySignature && this.eb.isBuilt && !$n) {
      if (!extension.isSigned) {
        throw new $Ip(
          localize(1837, null),
          "PackageNotSigned"
          /* ExtensionManagementErrorCode.PackageNotSigned */
        );
      }
      if (!verificationStatus) {
        throw new $Ip(
          localize(1838, null),
          "SignatureVerificationInternal"
          /* ExtensionManagementErrorCode.SignatureVerificationInternal */
        );
      }
      switch (verificationStatus) {
        case ExtensionSignatureVerificationCode.PackageIntegrityCheckFailed:
        case ExtensionSignatureVerificationCode.SignatureIsInvalid:
        case ExtensionSignatureVerificationCode.SignatureManifestIsInvalid:
        case ExtensionSignatureVerificationCode.SignatureIntegrityCheckFailed:
        case ExtensionSignatureVerificationCode.EntryIsMissing:
        case ExtensionSignatureVerificationCode.EntryIsTampered:
        case ExtensionSignatureVerificationCode.Untrusted:
        case ExtensionSignatureVerificationCode.CertificateRevoked:
        case ExtensionSignatureVerificationCode.SignatureIsNotValid:
        case ExtensionSignatureVerificationCode.SignatureArchiveHasTooManyEntries:
          throw new $Ip(
            localize(1839, null, verificationStatus),
            "SignatureVerificationFailed"
            /* ExtensionManagementErrorCode.SignatureVerificationFailed */
          );
      }
      throw new $Ip(
        localize(1840, null, verificationStatus),
        "SignatureVerificationInternal"
        /* ExtensionManagementErrorCode.SignatureVerificationInternal */
      );
    }
    return { location, verificationStatus };
  }
  async tb(extensionKey, location, options, token) {
    const local = await this.ab.extractUserExtension(extensionKey, $wc(location.fsPath), {
      isApplicationScoped: options.isApplicationScoped,
      isMachineScoped: options.isMachineScoped,
      isBuiltin: options.isBuiltin,
      installedTimestamp: Date.now(),
      pinned: options.installGivenVersion ? true : !!options.pinned,
      source: "vsix"
    }, options.keepExisting ?? true, token);
    return { local };
  }
  async ub(extension) {
    const collectFilesFromDirectory = async (dir) => {
      let entries = await Promises2.readdir(dir);
      entries = entries.map((e) => $vc(dir, e));
      const stats = await Promise.all(entries.map((e) => fs5.promises.stat(e)));
      let promise = Promise.resolve([]);
      stats.forEach((stat, index) => {
        const entry = entries[index];
        if (stat.isFile()) {
          promise = promise.then((result) => [...result, entry]);
        }
        if (stat.isDirectory()) {
          promise = promise.then((result) => collectFilesFromDirectory(entry).then((files2) => [...result, ...files2]));
        }
      });
      return promise;
    };
    const files = await collectFilesFromDirectory(extension.location.fsPath);
    return files.map((f) => ({ path: `extension/${$xc(extension.location.fsPath, f)}`, localPath: f }));
  }
  async vb({ added, removed }) {
    if (removed) {
      const removedExtensions = added && this.D.extUri.isEqual(removed.profileLocation, added.profileLocation) ? removed.extensions.filter((e) => added.extensions.every((identifier) => !$8p(identifier, e))) : removed.extensions;
      for (const identifier of removedExtensions) {
        this.F.info("Extensions removed from another source", identifier.id, removed.profileLocation.toString());
        this.u.fire({ identifier, profileLocation: removed.profileLocation });
      }
    }
    if (added) {
      const extensions = await this.getInstalled(1, added.profileLocation);
      const addedExtensions = extensions.filter((e) => added.extensions.some((identifier) => $8p(identifier, e.identifier)));
      this.s.fire(addedExtensions.map((local) => {
        this.F.info("Extensions added from another source", local.identifier.id, added.profileLocation.toString());
        return {
          identifier: local.identifier,
          local,
          profileLocation: added.profileLocation,
          operation: 1
          /* InstallOperation.None */
        };
      }));
    }
  }
  async xb() {
    this.B(this.ab.onExtract((resource) => this.wb.add(resource)));
    const stat = await this.jb.resolve(this.fb.userExtensionsLocation);
    for (const childStat of stat.children ?? []) {
      if (childStat.isDirectory) {
        this.wb.add(childStat.resource);
      }
    }
    this.B(this.jb.watch(this.fb.userExtensionsLocation));
    this.B(this.jb.onDidFilesChange((e) => this.yb(e)));
  }
  async yb(e) {
    if (!e.affects(
      this.fb.userExtensionsLocation,
      1
      /* FileChangeType.ADDED */
    )) {
      return;
    }
    const added = [];
    for (const resource of e.rawAdded) {
      if (this.wb.has(resource)) {
        continue;
      }
      if (!this.D.extUri.isEqual(this.D.extUri.dirname(resource), this.fb.userExtensionsLocation)) {
        continue;
      }
      if (this.D.extUri.isEqual(resource, this.D.extUri.joinPath(this.fb.userExtensionsLocation, ".obsolete"))) {
        continue;
      }
      if (this.D.extUri.basename(resource).startsWith(".")) {
        continue;
      }
      if (!(await this.jb.stat(resource)).isDirectory) {
        continue;
      }
      const extension = await this.ab.scanUserExtensionAtLocation(resource);
      if (extension && extension.installedTimestamp === void 0) {
        this.wb.add(resource);
        added.push(extension);
      }
    }
    if (added.length) {
      await this.zb(added.map((e2) => [e2, void 0]), this.H.defaultProfile.extensionsResource);
      this.F.info("Added extensions to default profile from external source", added.map((e2) => e2.identifier.id));
    }
  }
  async zb(extensions, profileLocation) {
    const localExtensions = extensions.map((e) => e[0]);
    await this.Ab(localExtensions);
    await this.gb.addExtensionsToProfile(extensions, profileLocation);
    this.s.fire(localExtensions.map((local) => ({ local, identifier: local.identifier, operation: 1, profileLocation })));
  }
  async Ab(extensions) {
    const uninstalled = await this.ab.getUninstalledExtensions();
    for (const extension of extensions) {
      const extensionKey = $9p.create(extension);
      if (!uninstalled[extensionKey.toString()]) {
        continue;
      }
      this.F.trace("Removing the extension from uninstalled list:", extensionKey.id);
      await this.ab.setInstalled(extensionKey);
      this.F.info("Removed the extension from uninstalled list:", extensionKey.id);
    }
  }
};
$jr = __decorate([
  __param(0, $Gp),
  __param(1, $tm),
  __param(2, $uk),
  __param(3, $8i),
  __param(4, $0q),
  __param(5, $6q),
  __param(6, $kp),
  __param(7, $Yi),
  __param(8, $ul),
  __param(9, $tj),
  __param(10, $Nk),
  __param(11, $5l),
  __param(12, $7l)
], $jr);
var $kr = class $kr2 extends $0c {
  constructor(n, s, t, u, w, y, z) {
    super();
    this.n = n;
    this.s = s;
    this.t = t;
    this.u = u;
    this.w = w;
    this.y = y;
    this.z = z;
    this.h = this.B(new $De());
    this.onExtract = this.h.event;
    this.j = new $Mc();
    this.m = new $Mc();
    this.c = $Ah(this.t.userExtensionsLocation, ".obsolete");
    this.g = new $7h();
  }
  async cleanUp() {
    await this.J();
    await this.I();
  }
  async scanExtensions(type2, profileLocation, productVersion) {
    try {
      const userScanOptions = { includeInvalid: true, profileLocation, productVersion };
      let scannedExtensions = [];
      if (type2 === null || type2 === 0) {
        let scanAllExtensionsPromise = this.j.get(profileLocation);
        if (!scanAllExtensionsPromise) {
          scanAllExtensionsPromise = this.t.scanAllExtensions({ includeInvalid: true, useCache: true }, userScanOptions, false).finally(() => this.j.delete(profileLocation));
          this.j.set(profileLocation, scanAllExtensionsPromise);
        }
        scannedExtensions.push(...await scanAllExtensionsPromise);
      } else if (type2 === 1) {
        let scanUserExtensionsPromise = this.m.get(profileLocation);
        if (!scanUserExtensionsPromise) {
          scanUserExtensionsPromise = this.t.scanUserExtensions(userScanOptions).finally(() => this.m.delete(profileLocation));
          this.m.set(profileLocation, scanUserExtensionsPromise);
        }
        scannedExtensions.push(...await scanUserExtensionsPromise);
      }
      scannedExtensions = type2 !== null ? scannedExtensions.filter((r) => r.type === type2) : scannedExtensions;
      return await Promise.all(scannedExtensions.map((extension) => this.H(extension)));
    } catch (error) {
      throw $3q(
        error,
        "Scanning"
        /* ExtensionManagementErrorCode.Scanning */
      );
    }
  }
  async scanAllUserExtensions(excludeOutdated) {
    try {
      const scannedExtensions = await this.t.scanUserExtensions({ includeAllVersions: !excludeOutdated, includeInvalid: true });
      return await Promise.all(scannedExtensions.map((extension) => this.H(extension)));
    } catch (error) {
      throw $3q(
        error,
        "Scanning"
        /* ExtensionManagementErrorCode.Scanning */
      );
    }
  }
  async scanUserExtensionAtLocation(location) {
    try {
      const scannedExtension = await this.t.scanExistingExtension(location, 1, { includeInvalid: true });
      if (scannedExtension) {
        return await this.H(scannedExtension);
      }
    } catch (error) {
      this.z.error(error);
    }
    return null;
  }
  async extractUserExtension(extensionKey, zipPath, metadata, removeIfExists, token) {
    const folderName = extensionKey.toString();
    const tempLocation = URI.file($vc(this.t.userExtensionsLocation.fsPath, `.${$jh()}`));
    const extensionLocation = URI.file($vc(this.t.userExtensionsLocation.fsPath, folderName));
    if (await this.s.exists(extensionLocation)) {
      if (!removeIfExists) {
        try {
          return await this.scanLocalExtension(
            extensionLocation,
            1
            /* ExtensionType.User */
          );
        } catch (error) {
          this.z.warn(`Error while scanning the existing extension at ${extensionLocation.path}. Deleting the existing extension and extracting it.`, $kb(error));
        }
      }
      try {
        await this.D(extensionKey.id, extensionLocation, "removeExisting");
      } catch (error) {
        throw new $Ip(
          localize(1841, null, extensionLocation.fsPath, extensionKey.id),
          "Delete"
          /* ExtensionManagementErrorCode.Delete */
        );
      }
    }
    try {
      if (token.isCancellationRequested) {
        throw new $fb();
      }
      try {
        this.z.trace(`Started extracting the extension from ${zipPath} to ${extensionLocation.fsPath}`);
        await $Zq(zipPath, tempLocation.fsPath, { sourcePath: "extension", overwrite: true }, token);
        this.z.info(`Extracted extension to ${extensionLocation}:`, extensionKey.id);
      } catch (e) {
        throw $cr(e);
      }
      try {
        await this.t.updateMetadata(tempLocation, metadata);
      } catch (error) {
        this.y.publicLog2("extension:extract", { extensionId: extensionKey.id, code: `${$Ll(error)}` });
        throw $3q(
          error,
          "UpdateMetadata"
          /* ExtensionManagementErrorCode.UpdateMetadata */
        );
      }
      if (token.isCancellationRequested) {
        throw new $fb();
      }
      try {
        this.z.trace(`Started renaming the extension from ${tempLocation.fsPath} to ${extensionLocation.fsPath}`);
        await this.G(tempLocation.fsPath, extensionLocation.fsPath);
        this.z.info("Renamed to", extensionLocation.fsPath);
      } catch (error) {
        if (error.code === "ENOTEMPTY") {
          this.z.info(`Rename failed because extension was installed by another source. So ignoring renaming.`, extensionKey.id);
          try {
            await this.s.del(tempLocation, { recursive: true });
          } catch (e) {
          }
        } else {
          this.z.info(`Rename failed because of ${$kb(error)}. Deleted from extracted location`, tempLocation);
          throw error;
        }
      }
      this.h.fire(extensionLocation);
    } catch (error) {
      try {
        await this.s.del(tempLocation, { recursive: true });
      } catch (e) {
      }
      throw error;
    }
    return this.scanLocalExtension(
      extensionLocation,
      1
      /* ExtensionType.User */
    );
  }
  async scanMetadata(local, profileLocation) {
    if (profileLocation) {
      const extension = await this.C(local, profileLocation);
      return extension?.metadata;
    } else {
      return this.t.scanMetadata(local.location);
    }
  }
  async C(local, profileLocation) {
    const extensions = await this.u.scanProfileExtensions(profileLocation);
    return extensions.find((e) => $8p(e.identifier, local.identifier));
  }
  async updateMetadata(local, metadata, profileLocation) {
    try {
      if (profileLocation) {
        await this.u.updateMetadata([[local, metadata]], profileLocation);
      } else {
        await this.t.updateMetadata(local.location, metadata);
      }
    } catch (error) {
      this.y.publicLog2("extension:extract", { extensionId: local.identifier.id, code: `${$Ll(error)}`, isProfile: !!profileLocation });
      throw $3q(
        error,
        "UpdateMetadata"
        /* ExtensionManagementErrorCode.UpdateMetadata */
      );
    }
    return this.scanLocalExtension(local.location, local.type, profileLocation);
  }
  async getUninstalledExtensions() {
    try {
      return await this.F();
    } catch (error) {
      throw $3q(
        error,
        "ReadUninstalled"
        /* ExtensionManagementErrorCode.ReadUninstalled */
      );
    }
  }
  async setUninstalled(...extensions) {
    const extensionKeys = extensions.map((e) => $9p.create(e));
    await this.F((uninstalled) => extensionKeys.forEach((extensionKey) => {
      uninstalled[extensionKey.toString()] = true;
      this.z.info("Marked extension as uninstalled", extensionKey.toString());
    }));
  }
  async setInstalled(extensionKey) {
    try {
      await this.F((uninstalled) => delete uninstalled[extensionKey.toString()]);
    } catch (error) {
      throw $3q(
        error,
        "UnsetUninstalled"
        /* ExtensionManagementErrorCode.UnsetUninstalled */
      );
    }
  }
  async removeExtension(extension, type2) {
    if (this.w.extUri.isEqualOrParent(extension.location, this.t.userExtensionsLocation)) {
      return this.D(extension.identifier.id, extension.location, type2);
    }
  }
  async removeUninstalledExtension(extension) {
    await this.removeExtension(extension, "uninstalled");
    await this.F((uninstalled) => delete uninstalled[$9p.create(extension).toString()]);
  }
  async copyExtension(extension, fromProfileLocation, toProfileLocation, metadata) {
    const source = await this.C(extension, fromProfileLocation);
    const target = await this.C(extension, toProfileLocation);
    metadata = { ...source?.metadata, ...metadata };
    if (target) {
      if (this.w.extUri.isEqual(target.location, extension.location)) {
        await this.u.updateMetadata([[extension, { ...target.metadata, ...metadata }]], toProfileLocation);
      } else {
        const targetExtension = await this.scanLocalExtension(target.location, extension.type, toProfileLocation);
        await this.u.removeExtensionFromProfile(targetExtension, toProfileLocation);
        await this.u.addExtensionsToProfile([[extension, { ...target.metadata, ...metadata }]], toProfileLocation);
      }
    } else {
      await this.u.addExtensionsToProfile([[extension, metadata]], toProfileLocation);
    }
    return this.scanLocalExtension(extension.location, extension.type, toProfileLocation);
  }
  async copyExtensions(fromProfileLocation, toProfileLocation, productVersion) {
    const fromExtensions = await this.scanExtensions(1, fromProfileLocation, productVersion);
    const extensions = await Promise.all(fromExtensions.filter((e) => !e.isApplicationScoped).map(async (e) => [e, await this.scanMetadata(e, fromProfileLocation)]));
    await this.u.addExtensionsToProfile(extensions, toProfileLocation);
  }
  async D(id2, location, type2) {
    this.z.trace(`Deleting ${type2} extension from disk`, id2, location.fsPath);
    const renamedLocation = this.w.extUri.joinPath(this.w.extUri.dirname(location), `${this.w.extUri.basename(location)}.${$Nj($jh()).toString(16)}${DELETED_FOLDER_POSTFIX}`);
    await this.G(location.fsPath, renamedLocation.fsPath);
    await this.s.del(renamedLocation, { recursive: true });
    this.z.info(`Deleted ${type2} extension from disk`, id2, location.fsPath);
  }
  F(updateFn) {
    return this.g.queue(async () => {
      let raw;
      try {
        const content = await this.s.readFile(this.c, "utf8");
        raw = content.value.toString();
      } catch (error) {
        if ($Ll(error) !== 1) {
          throw error;
        }
      }
      let uninstalled = {};
      if (raw) {
        try {
          uninstalled = JSON.parse(raw);
        } catch (e) {
        }
      }
      if (updateFn) {
        updateFn(uninstalled);
        if (Object.keys(uninstalled).length) {
          await this.s.writeFile(this.c, $7e.fromString(JSON.stringify(uninstalled)));
        } else {
          await this.s.del(this.c);
        }
      }
      return uninstalled;
    });
  }
  async G(extractPath, renamePath) {
    try {
      await Promises2.rename(
        extractPath,
        renamePath,
        2 * 60 * 1e3
        /* Retry for 2 minutes */
      );
    } catch (error) {
      throw $3q(
        error,
        "Rename"
        /* ExtensionManagementErrorCode.Rename */
      );
    }
  }
  async scanLocalExtension(location, type2, profileLocation) {
    try {
      if (profileLocation) {
        const scannedExtensions = await this.t.scanUserExtensions({ profileLocation });
        const scannedExtension = scannedExtensions.find((e) => this.w.extUri.isEqual(e.location, location));
        if (scannedExtension) {
          return await this.H(scannedExtension);
        }
      } else {
        const scannedExtension = await this.t.scanExistingExtension(location, type2, { includeInvalid: true });
        if (scannedExtension) {
          return await this.H(scannedExtension);
        }
      }
      throw new $Ip(
        localize(1842, null, location.path),
        "ScanningExtension"
        /* ExtensionManagementErrorCode.ScanningExtension */
      );
    } catch (error) {
      throw $3q(
        error,
        "ScanningExtension"
        /* ExtensionManagementErrorCode.ScanningExtension */
      );
    }
  }
  async H(extension) {
    const stat = await this.s.resolve(extension.location);
    let readmeUrl;
    let changelogUrl;
    if (stat.children) {
      readmeUrl = stat.children.find(({ name }) => /^readme(\.txt|\.md|)$/i.test(name))?.resource;
      changelogUrl = stat.children.find(({ name }) => /^changelog(\.txt|\.md|)$/i.test(name))?.resource;
    }
    return {
      identifier: extension.identifier,
      type: extension.type,
      isBuiltin: extension.isBuiltin || !!extension.metadata?.isBuiltin,
      location: extension.location,
      manifest: extension.manifest,
      targetPlatform: extension.targetPlatform,
      validations: extension.validations,
      isValid: extension.isValid,
      readmeUrl,
      changelogUrl,
      publisherDisplayName: extension.metadata?.publisherDisplayName,
      publisherId: extension.metadata?.publisherId || null,
      isApplicationScoped: !!extension.metadata?.isApplicationScoped,
      isMachineScoped: !!extension.metadata?.isMachineScoped,
      isPreReleaseVersion: !!extension.metadata?.isPreReleaseVersion,
      hasPreReleaseVersion: !!extension.metadata?.hasPreReleaseVersion,
      preRelease: !!extension.metadata?.preRelease,
      installedTimestamp: extension.metadata?.installedTimestamp,
      updated: !!extension.metadata?.updated,
      pinned: !!extension.metadata?.pinned,
      isWorkspaceScoped: false,
      source: extension.metadata?.source ?? (extension.identifier.uuid ? "gallery" : "vsix")
    };
  }
  async I() {
    const uninstalled = await this.getUninstalledExtensions();
    if (Object.keys(uninstalled).length === 0) {
      this.z.debug(`No uninstalled extensions found.`);
      return;
    }
    this.z.debug(`Removing uninstalled extensions:`, Object.keys(uninstalled));
    const extensions = await this.t.scanUserExtensions({ includeAllVersions: true, includeUninstalled: true, includeInvalid: true });
    const installed = /* @__PURE__ */ new Set();
    for (const e of extensions) {
      if (!uninstalled[$9p.create(e).toString()]) {
        installed.add(e.identifier.id.toLowerCase());
      }
    }
    try {
      const byExtension = $bq(extensions, (e) => e.identifier);
      await Promises.settled(byExtension.map(async (e) => {
        const latest = e.sort((a, b) => rcompare(a.manifest.version, b.manifest.version))[0];
        if (!installed.has(latest.identifier.id.toLowerCase())) {
          await this.n(await this.H(latest));
        }
      }));
    } catch (error) {
      this.z.error(error);
    }
    const toRemove = extensions.filter((e) => e.metadata && uninstalled[$9p.create(e).toString()]);
    await Promise.allSettled(toRemove.map((e) => this.removeUninstalledExtension(e)));
  }
  async J() {
    this.z.trace("ExtensionManagementService#removeTempDeleteFolders");
    let stat;
    try {
      stat = await this.s.resolve(this.t.userExtensionsLocation);
    } catch (error) {
      if ($Ll(error) !== 1) {
        this.z.error(error);
      }
      return;
    }
    if (!stat?.children) {
      return;
    }
    try {
      await Promise.allSettled(stat.children.map(async (child) => {
        if (!child.isDirectory || !child.name.endsWith(DELETED_FOLDER_POSTFIX)) {
          return;
        }
        this.z.trace("Deleting the temporarily deleted folder", child.resource.toString());
        try {
          await this.s.del(child.resource, { recursive: true });
          this.z.trace("Deleted the temporarily deleted folder", child.resource.toString());
        } catch (error) {
          if ($Ll(error) !== 1) {
            this.z.error(error);
          }
        }
      }));
    } catch (error) {
    }
  }
};
$kr = __decorate([
  __param(1, $ul),
  __param(2, $0q),
  __param(3, $6q),
  __param(4, $5l),
  __param(5, $tm),
  __param(6, $uk)
], $kr);
var InstallExtensionInProfileTask = class InstallExtensionInProfileTask2 extends $4q {
  get operation() {
    return this.options.operation ?? this.j;
  }
  get verificationStatus() {
    return this.k;
  }
  constructor(l, manifest, source, options, m, n, o, p, q, s, t, u) {
    super();
    this.l = l;
    this.manifest = manifest;
    this.source = source;
    this.options = options;
    this.m = m;
    this.n = n;
    this.o = o;
    this.p = p;
    this.q = q;
    this.s = s;
    this.t = t;
    this.u = u;
    this.j = 2;
    this.identifier = this.l.identifier;
  }
  async h(token) {
    const installed = await this.n.scanExtensions(1, this.options.profileLocation, this.options.productVersion);
    const existingExtension = installed.find((i) => $8p(i.identifier, this.identifier));
    if (existingExtension) {
      this.j = 3;
    }
    const metadata = {
      isApplicationScoped: this.options.isApplicationScoped || existingExtension?.isApplicationScoped,
      isMachineScoped: this.options.isMachineScoped || existingExtension?.isMachineScoped,
      isBuiltin: this.options.isBuiltin || existingExtension?.isBuiltin,
      isSystem: existingExtension?.type === 0 ? true : void 0,
      installedTimestamp: Date.now(),
      pinned: this.options.installGivenVersion ? true : this.options.pinned ?? existingExtension?.pinned,
      source: this.source instanceof URI ? "vsix" : "gallery"
    };
    let local;
    if (this.source instanceof URI) {
      if (existingExtension) {
        if (this.l.equals(new $9p(existingExtension.identifier, existingExtension.manifest.version))) {
          try {
            await this.n.removeExtension(existingExtension, "existing");
          } catch (e) {
            throw new Error(localize(1843, null, this.manifest.displayName || this.manifest.name));
          }
        }
      }
      const existingWithSameVersion = await this.w(this.l);
      if (existingWithSameVersion) {
        try {
          await this.n.removeExtension(existingWithSameVersion, "existing");
        } catch (e) {
          throw new Error(localize(1844, null, this.manifest.displayName || this.manifest.name));
        }
      }
    } else {
      metadata.id = this.source.identifier.uuid;
      metadata.publisherId = this.source.publisherId;
      metadata.publisherDisplayName = this.source.publisherDisplayName;
      metadata.targetPlatform = this.source.properties.targetPlatform;
      metadata.updated = !!existingExtension;
      metadata.isPreReleaseVersion = this.source.properties.isPreReleaseVersion;
      metadata.hasPreReleaseVersion = existingExtension?.hasPreReleaseVersion || this.source.properties.isPreReleaseVersion;
      metadata.preRelease = $Eg(this.options.preRelease) ? this.options.preRelease : this.options.installPreReleaseVersion || this.source.properties.isPreReleaseVersion || existingExtension?.preRelease;
      if (existingExtension && existingExtension.type !== 0 && existingExtension.manifest.version === this.source.version) {
        return this.n.updateMetadata(existingExtension, metadata, this.options.profileLocation);
      }
      local = await this.w(this.l);
    }
    if (token.isCancellationRequested) {
      throw $3q(new $fb());
    }
    if (!local) {
      const result2 = await this.m(this.operation, token);
      local = result2.local;
      this.k = result2.verificationStatus;
    }
    if (this.o.extUri.isEqual(this.q.defaultProfile.extensionsResource, this.options.profileLocation)) {
      try {
        await this.s.initializeDefaultProfileExtensions();
      } catch (error) {
        throw $3q(
          error,
          "IntializeDefaultProfile"
          /* ExtensionManagementErrorCode.IntializeDefaultProfile */
        );
      }
    }
    if (token.isCancellationRequested) {
      throw $3q(new $fb());
    }
    try {
      await this.t.addExtensionsToProfile([[local, metadata]], this.options.profileLocation, !local.isValid);
    } catch (error) {
      throw $3q(
        error,
        "AddToProfile"
        /* ExtensionManagementErrorCode.AddToProfile */
      );
    }
    const result = await this.n.scanLocalExtension(local.location, 1, this.options.profileLocation);
    if (!result) {
      throw new $Ip(
        "Cannot find the installed extension",
        "InstalledExtensionNotFound"
        /* ExtensionManagementErrorCode.InstalledExtensionNotFound */
      );
    }
    if (this.source instanceof URI) {
      this.x(local, token);
    }
    return result;
  }
  async w(extensionKey) {
    const uninstalled = await this.n.getUninstalledExtensions();
    if (!uninstalled[extensionKey.toString()]) {
      return void 0;
    }
    this.u.trace("Removing the extension from uninstalled list:", extensionKey.id);
    await this.n.setInstalled(extensionKey);
    this.u.info("Removed the extension from uninstalled list:", extensionKey.id);
    const userExtensions = await this.n.scanAllUserExtensions(true);
    return userExtensions.find((i) => $9p.create(i).equals(extensionKey));
  }
  async x(extension, token) {
    try {
      let [galleryExtension] = await this.p.getExtensions([{ id: extension.identifier.id, version: extension.manifest.version }], token);
      if (!galleryExtension) {
        [galleryExtension] = await this.p.getExtensions([{ id: extension.identifier.id }], token);
      }
      if (galleryExtension) {
        const metadata = {
          id: galleryExtension.identifier.uuid,
          publisherDisplayName: galleryExtension.publisherDisplayName,
          publisherId: galleryExtension.publisherId,
          isPreReleaseVersion: galleryExtension.properties.isPreReleaseVersion,
          hasPreReleaseVersion: extension.hasPreReleaseVersion || galleryExtension.properties.isPreReleaseVersion,
          preRelease: galleryExtension.properties.isPreReleaseVersion || this.options.installPreReleaseVersion
        };
        await this.n.updateMetadata(extension, metadata, this.options.profileLocation);
      }
    } catch (error) {
    }
  }
};
InstallExtensionInProfileTask = __decorate([
  __param(6, $5l),
  __param(7, $Gp),
  __param(8, $7l),
  __param(9, $0q),
  __param(10, $6q),
  __param(11, $uk)
], InstallExtensionInProfileTask);
var UninstallExtensionInProfileTask = class extends $4q {
  constructor(extension, options, j) {
    super();
    this.extension = extension;
    this.options = options;
    this.j = j;
  }
  async h(token) {
    await this.j.removeExtensionFromProfile(this.extension, this.options.profileLocation);
  }
};

// out-build/vs/platform/extensionRecommendations/common/extensionRecommendations.js
var RecommendationSource;
(function(RecommendationSource2) {
  RecommendationSource2[RecommendationSource2["FILE"] = 1] = "FILE";
  RecommendationSource2[RecommendationSource2["WORKSPACE"] = 2] = "WORKSPACE";
  RecommendationSource2[RecommendationSource2["EXE"] = 3] = "EXE";
})(RecommendationSource || (RecommendationSource = {}));
var RecommendationsNotificationResult;
(function(RecommendationsNotificationResult2) {
  RecommendationsNotificationResult2["Ignored"] = "ignored";
  RecommendationsNotificationResult2["Cancelled"] = "cancelled";
  RecommendationsNotificationResult2["TooMany"] = "toomany";
  RecommendationsNotificationResult2["IncompatibleWindow"] = "incompatibleWindow";
  RecommendationsNotificationResult2["Accepted"] = "reacted";
})(RecommendationsNotificationResult || (RecommendationsNotificationResult = {}));
var $L_b = $Zi("IExtensionRecommendationNotificationService");

// 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 handle2 = 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(handle2, 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(handle2);
  }
}
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/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, type2]) => {
          try {
            const childResource = providerExtUri.joinPath(resource, name);
            const childStat = resolveMetadata ? await provider.stat(childResource) : { type: type2 };
            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((resolve, reject) => {
      this.cb.queueFor(resource, async () => {
        try {
          const content = await this.C(provider, resource, options, token);
          resolve(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 handle2 = await provider.open(resource, { create: true, unlock: options?.unlock ?? false });
      try {
        if ($Se(readableOrStreamOrBufferedStream) || $Te(readableOrStreamOrBufferedStream)) {
          await this.eb(provider, handle2, readableOrStreamOrBufferedStream);
        } else {
          await this.fb(provider, handle2, readableOrStreamOrBufferedStream);
        }
      } catch (error) {
        throw $Il(error);
      } finally {
        await provider.close(handle2);
      }
    }, this.R(provider).providerExtUri);
  }
  async eb(provider, handle2, streamOrBufferedStream) {
    let posInFile = 0;
    let stream;
    if ($Te(streamOrBufferedStream)) {
      if (streamOrBufferedStream.buffer.length > 0) {
        const chunk = $7e.concat(streamOrBufferedStream.buffer);
        await this.gb(provider, handle2, chunk, chunk.byteLength, posInFile, 0);
        posInFile += chunk.byteLength;
      }
      if (streamOrBufferedStream.ended) {
        return;
      }
      stream = streamOrBufferedStream.stream;
    } else {
      stream = streamOrBufferedStream;
    }
    return new Promise((resolve, reject) => {
      $Ye(stream, {
        onData: async (chunk) => {
          stream.pause();
          try {
            await this.gb(provider, handle2, chunk, chunk.byteLength, posInFile, 0);
          } catch (error) {
            return reject(error);
          }
          posInFile += chunk.byteLength;
          setTimeout(() => stream.resume());
        },
        onError: (error) => reject(error),
        onEnd: () => resolve()
      });
    });
  }
  async fb(provider, handle2, readable) {
    let posInFile = 0;
    let chunk;
    while ((chunk = readable.read()) !== null) {
      await this.gb(provider, handle2, chunk, chunk.byteLength, posInFile, 0);
      posInFile += chunk.byteLength;
    }
  }
  async gb(provider, handle2, buffer, length, posInFile, posInBuffer) {
    let totalBytesWritten = 0;
    while (totalBytesWritten < length) {
      const bytesWritten = await provider.write(handle2, 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/files/node/diskFileSystemProvider.js
import { promises as promises10 } from "fs";

// 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(path2, basename) {
    if (!$Yg(path2, arg2.base, !$n)) {
      return null;
    }
    return parsedPattern($Ff(path2.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(path2, basename) {
    return typeof path2 === "string" && path2.endsWith(base) ? pattern : null;
  };
}
function trivia2(base, pattern) {
  const slashBase = `/${base}`;
  const backslashBase = `\\${base}`;
  const parsedPattern = function(path2, basename) {
    if (typeof path2 !== "string") {
      return null;
    }
    if (basename) {
      return basename === base ? pattern : null;
    }
    return path2 === base || path2.endsWith(slashBase) || path2.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(path2, basename) {
    for (let i = 0, n = parsedPatterns.length; i < n; i++) {
      if (parsedPatterns[i](path2, 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(path2, basename) {
      return typeof path2 === "string" && (path2 === nativePath || path2.endsWith(nativePathEnd) || !usingPosixSep && (path2 === targetPath || path2.endsWith(targetPathEnd))) ? pattern : null;
    };
  } else {
    parsedPattern = function(path2, basename) {
      return typeof path2 === "string" && (path2 === nativePath || !usingPosixSep && path2 === targetPath) ? pattern : null;
    };
  }
  parsedPattern.allPaths = [(matchPathEnds ? "*/" : "./") + targetPath];
  return parsedPattern;
}
function toRegExp(pattern) {
  try {
    const regExp = new RegExp(`^${parseRegExp(pattern)}$`);
    return function(path2) {
      regExp.lastIndex = 0;
      return typeof path2 === "string" && regExp.test(path2) ? 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(path2, basename) {
      return !!parsedPattern(path2, 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(path2, basename) {
      let resultPromises = void 0;
      for (let i = 0, n = parsedPatterns.length; i < n; i++) {
        const result = parsedPatterns[i](path2, 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(path2, 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(path2);
        }
        if (!name) {
          name = base.substr(0, base.length - $Ac(path2).length);
        }
      }
      const result = parsedPattern(path2, 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 = (path2, basename, name, hasSibling) => {
        if (!hasSibling || !parsedPattern(path2, 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(path2, basename) {
    if (typeof path2 !== "string") {
      return null;
    }
    if (!basename) {
      let i;
      for (i = path2.length; i > 0; i--) {
        const ch = path2.charCodeAt(i - 1);
        if (ch === 47 || ch === 92) {
          break;
        }
      }
      basename = path2.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(request2) {
  return typeof request2.correlationId === "number";
}
function $or(request2) {
  return request2.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(path2, pattern) {
  if (typeof pattern === "string" && !pattern.startsWith($Qk) && !$uc(pattern)) {
    return { base: path2, pattern };
  }
  return pattern;
}
function $vr(path2, patterns) {
  const parsedPatterns = [];
  for (const pattern of patterns) {
    parsedPatterns.push($Uk($ur(path2, 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/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 request2 = this.r(resource, opts);
    const remove = $5b(this.j, request2);
    this.s();
    return $8c(() => {
      remove();
      this.s();
    });
  }
  r(resource, opts) {
    const request2 = {
      path: this.L(resource),
      excludes: opts.excludes,
      includes: opts.includes,
      recursive: opts.recursive,
      filter: opts.filter,
      correlationId: opts.correlationId
    };
    if ($or(request2)) {
      const usePolling = this.b?.watcher?.recursive?.usePolling;
      if (usePolling === true) {
        request2.pollingInterval = this.b?.watcher?.recursive?.pollingInterval ?? 5e3;
      } else if (Array.isArray(usePolling)) {
        if (usePolling.includes(request2.path)) {
          request2.pollingInterval = this.b?.watcher?.recursive?.pollingInterval ?? 5e3;
        }
      }
    }
    return request2;
  }
  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 request2 = {
      path: this.L(resource),
      excludes: opts.excludes,
      includes: opts.includes,
      recursive: false,
      filter: opts.filter,
      correlationId: opts.correlationId
    };
    const remove = $5b(this.y, request2);
    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 as fork2 } 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 log(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/node/processes.js
import { promises as promises7 } from "fs";

// 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 $Gm(env2) {
  if (!env2) {
    return;
  }
  delete env2["DEBUG"];
  if ($n) {
    delete env2["LD_PRELOAD"];
  }
}

// out-build/vs/base/node/processes.js
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(path2) {
      if (await Promises2.exists(path2)) {
        let statValue;
        try {
          statValue = await promises7.stat(path2);
        } catch (e) {
          if (e.message.startsWith("EACCES")) {
            statValue = await promises7.lstat(path2);
          }
        }
        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/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 = fork2(this.i, args, forkOpts);
      const onMessageEmitter = new $De();
      const onRawMessage = Event.fromNodeEventEmitter(this.d, "message", (msg) => msg);
      const rawMessageDisposable = onRawMessage((msg) => {
        if ($zr(msg)) {
          log(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 protocol = { send, onMessage };
      this.f = new $Ci(protocol);
      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", (code, signal) => {
        process.removeListener("exit", onExit);
        rawMessageDisposable.dispose();
        this.c.forEach((r) => $5c(r));
        this.c.clear();
        if (code !== 0 && signal !== "SIGTERM") {
          console.warn('IPC "' + this.j.serverName + '" crashed with exit code ' + code + " and signal " + signal);
        }
        this.b?.cancel();
        this.o();
        this.h.fire({ code, 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, signal }) => this.t(`terminated by itself with code ${code}, 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((request2) => this.z({
      id: this.u(request2),
      correlationId: this.t(request2) ? request2.correlationId : void 0,
      path: request2.path
    })));
  }
  t(request2) {
    return $nr(request2);
  }
  u(request2) {
    if (this.t(request2)) {
      return request2.correlationId;
    } else {
      return $Nj(request2);
    }
  }
  async watch(requests) {
    if (!this.s.isSettled) {
      this.s.complete();
    }
    this.s = new $ki();
    try {
      this.g.clear();
      this.h.clear();
      for (const request2 of requests) {
        if (this.t(request2)) {
          this.g.set(request2.correlationId, request2);
        } else {
          this.h.set(this.u(request2), request2);
        }
      }
      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, request2] of [...this.h, ...this.g]) {
      if (!this.j.has(id2)) {
        nonSuspendedRequests.push(request2);
      }
    }
    return this.n.trigger(() => this.N(nonSuspendedRequests), delayed ? this.y() : 0);
  }
  y() {
    return 800;
  }
  isSuspended(request2) {
    const id2 = this.u(request2);
    return this.m.has(id2) ? "polling" : this.j.has(id2);
  }
  async z(request2) {
    if (this.j.has(request2.id)) {
      return;
    }
    const disposables = new $9c();
    this.j.set(request2.id, disposables);
    await this.s.p;
    if (disposables.isDisposed) {
      return;
    }
    this.D(request2, disposables);
    this.w(
      true
      /* delay this call as we might accumulate many failing watch requests on startup */
    );
  }
  C(request2) {
    this.j.deleteAndDispose(request2.id);
    this.m.delete(request2.id);
    this.w(false);
  }
  D(request2, disposables) {
    if (this.F(request2, disposables)) {
      this.P(`reusing an existing recursive watcher to monitor ${request2.path}`);
      this.m.delete(request2.id);
    } else {
      this.G(request2, disposables);
      this.m.add(request2.id);
    }
  }
  F(request2, disposables) {
    const subscription = this.O?.subscribe(request2.path, (error, change) => {
      if (disposables.isDisposed) {
        return;
      }
      if (error) {
        this.D(request2, disposables);
      } else if (change?.type === 1) {
        this.H(request2);
      }
    });
    if (subscription) {
      disposables.add(subscription);
      return true;
    }
    return false;
  }
  G(request2, 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(request2);
      }
    };
    this.P(`starting fs.watchFile() on ${request2.path} (correlationId: ${request2.correlationId})`);
    try {
      watchFile(request2.path, { persistent: false, interval: this.r }, watchFileCallback);
    } catch (error) {
      this.Q(`fs.watchFile() failed with error ${error} on path ${request2.path} (correlationId: ${request2.correlationId})`);
    }
    disposables.add($8c(() => {
      this.P(`stopping fs.watchFile() on ${request2.path} (correlationId: ${request2.correlationId})`);
      try {
        unwatchFile(request2.path, watchFileCallback);
      } catch (error) {
        this.Q(`fs.unwatchFile() failed with error ${error} on path ${request2.path} (correlationId: ${request2.correlationId})`);
      }
    }));
  }
  H(request2) {
    this.P(`detected ${request2.path} exists again, resuming watcher (correlationId: ${request2.correlationId})`);
    const event = { resource: URI.file(request2.path), type: 1, cId: request2.correlationId };
    this.a.fire([event]);
    this.J(event, request2);
    this.C(request2);
  }
  I(stats) {
    return stats.ctimeMs === 0 && stats.ino === 0;
  }
  async stop() {
    this.j.clearAndDisposeAll();
    this.m.clear();
  }
  J(event, request2) {
    if (this.R) {
      const traceMsg = ` >> normalized ${event.type === 1 ? "[ADDED]" : event.type === 2 ? "[DELETED]" : "[CHANGED]"} ${event.resource.fsPath}`;
      this.L(traceMsg, request2);
    }
  }
  L(message, request2) {
    if (this.R) {
      this.P(`${message}${typeof request2.correlationId === "number" ? ` <${request2.correlationId}> ` : ``}`);
    }
  }
  M(request2) {
    return `${request2.path} (excludes: ${request2.excludes.length > 0 ? request2.excludes : "<none>"}, includes: ${request2.includes && request2.includes.length > 0 ? JSON.stringify(request2.includes) : "<all>"}, filter: ${$xr(request2.filter)}, correlationId: ${typeof request2.correlationId === "number" ? request2.correlationId : "<none>"})`;
  }
  async setVerboseLogging(enabled) {
    this.R = enabled;
  }
};

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

// out-build/vs/base/node/extpath.js
import * as fs6 from "fs";
async function $Ir(path2, token) {
  if ($n) {
    return path2;
  }
  const dir = $yc(path2);
  if (path2 === dir) {
    return path2;
  }
  const name = ($zc(path2) || path2).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;
}

// 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 promises9.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(request2) {
    let realPath = request2.path;
    try {
      realPath = await Promises2.realpath(request2.path);
      if (request2.path === realPath) {
        realPath = await $Ir(request2.path, this.m.token) ?? request2.path;
      }
      if (request2.path !== realPath) {
        this.Q(`correcting a path to watch that seems to be a symbolic link or wrong casing (original: ${request2.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", (code, signal) => {
        if (cts.token.isCancellationRequested) {
          return;
        }
        this.O(`Failed to watch ${realPath} for changes using fs.watch() (${code}, ${signal})`);
        this.D();
      });
      watcher.on("change", (type2, raw) => {
        if (cts.token.isCancellationRequested) {
          return;
        }
        if (this.z) {
          this.R(`[raw] ["${type2}"] ${raw}`);
        }
        let changedFileName = "";
        if (raw) {
          changedFileName = raw.toString();
          if ($m) {
            changedFileName = $Hm(changedFileName);
          }
        }
        if (!changedFileName || type2 !== "change" && type2 !== "rename") {
          return;
        }
        if (isDirectory) {
          if (type2 === "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 type3;
              if (fileExists) {
                if (folderChildren.has(changedFileName)) {
                  type3 = 0;
                } else {
                  type3 = 1;
                  folderChildren.add(changedFileName);
                }
              } else {
                folderChildren.delete(changedFileName);
                type3 = 2;
              }
              this.L({ resource: $Ah(requestResource, changedFileName), type: type3, cId: this.s.correlationId });
            }, _$Lr.a);
            mapPathToStatDisposable.set(changedFileName, $8c(() => clearTimeout(timeoutHandle)));
          } else {
            let type3;
            if (folderChildren.has(changedFileName)) {
              type3 = 0;
            } else {
              type3 = 1;
              folderChildren.add(changedFileName);
            }
            this.L({ resource: $Ah(requestResource, changedFileName), type: type3, cId: this.s.correlationId });
          }
        } else {
          if (type2 === "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(path2) {
    if ($n) {
      return Promises2.exists(path2);
    }
    try {
      const pathBasename = $zc(path2);
      const children = await Promises2.readdir($yc(path2));
      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 request2 of requests) {
      const watcher = this.W(request2);
      if (watcher && $Yk(watcher.request.excludes, request2.excludes) && $Yk(watcher.request.includes, request2.includes)) {
        watchersToStop.delete(watcher);
      } else {
        requestsToStart.push(request2);
      }
    }
    if (requestsToStart.length) {
      this.P(`Request to start watching: ${requestsToStart.map((request2) => this.M(request2)).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 request2 of requestsToStart) {
      this.X(request2);
    }
  }
  W(request2) {
    for (const watcher of this.watchers) {
      if (typeof request2.correlationId === "number" || typeof watcher.request.correlationId === "number") {
        if (watcher.request.correlationId === request2.correlationId) {
          return watcher;
        }
      } else {
        if ($Xg(
          watcher.request.path,
          request2.path,
          !$n
          /* ignorecase */
        )) {
          return watcher;
        }
      }
    }
    return void 0;
  }
  X(request2) {
    const instance = new $Lr(request2, this.O, (changes) => this.a.fire(changes), () => this.c.fire(request2), (msg) => this.b.fire(msg), this.R);
    const watcher = { request: request2, 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 request2 of requests) {
      const path2 = $n ? request2.path : request2.path.toLowerCase();
      let requestsForCorrelation = mapCorrelationtoRequests.get(request2.correlationId);
      if (!requestsForCorrelation) {
        requestsForCorrelation = /* @__PURE__ */ new Map();
        mapCorrelationtoRequests.set(request2.correlationId, requestsForCorrelation);
      }
      if (requestsForCorrelation.has(path2)) {
        this.P(`ignoring a request for watching who's path is already watched: ${this.M(request2)}`);
      }
      requestsForCorrelation.set(path2, request2);
    }
    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 type2;
          if (child.isSymbolicLink()) {
            type2 = (await this.stat($Ah(resource, child.name))).type;
          } else {
            type2 = this.P(child);
          }
          result.push([child.name, type2]);
        } catch (error) {
          this.a.trace(error);
        }
      }));
      return result;
    } catch (error) {
      throw this.ib(error);
    }
  }
  P(entry, symbolicLink) {
    let type2;
    if (symbolicLink?.dangling) {
      type2 = FileType.Unknown;
    } else if (entry.isFile()) {
      type2 = FileType.File;
    } else if (entry.isDirectory()) {
      type2 = FileType.Directory;
    } else {
      type2 = FileType.Unknown;
    }
    if (symbolicLink) {
      type2 |= FileType.SymbolicLink;
    }
    return type2;
  }
  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 promises10.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 handle2 = 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);
          }
        }
      }
      handle2 = await this.open(resource, { create: true, unlock: opts.unlock }, disableWriteLock);
      await this.write(handle2, 0, content, 0, content.byteLength);
    } catch (error) {
      throw await this.jb(resource, error);
    } finally {
      if (typeof handle2 === "number") {
        await this.close(handle2);
      }
    }
  }
  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 promises10.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 promises10.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 promises10.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 promises10.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 promises10.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 promises10.mkdir($yc(toFilePath), { recursive: true });
      }
      await promises10.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 code;
    switch (error.code) {
      case "ENOENT":
        code = FileSystemProviderErrorCode.FileNotFound;
        break;
      case "EISDIR":
        code = FileSystemProviderErrorCode.FileIsADirectory;
        break;
      case "ENOTDIR":
        code = FileSystemProviderErrorCode.FileNotADirectory;
        break;
      case "EEXIST":
        code = FileSystemProviderErrorCode.FileExists;
        break;
      case "EPERM":
      case "EACCES":
        code = 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.`;
        code = FileSystemProviderErrorCode.Unknown;
        break;
      default:
        code = FileSystemProviderErrorCode.Unknown;
    }
    return $Hl(resultError, code);
  }
  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/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/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/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/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(type2, name) {
    this.type = type2;
    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/languagePacks/node/languagePacks.js
import * as fs7 from "fs";
import { createHash as createHash3 } from "crypto";
var $xs = class $xs2 extends $ws {
  constructor(h, environmentService, extensionGalleryService, j) {
    super(extensionGalleryService);
    this.h = h;
    this.j = j;
    this.g = this.B(new LanguagePacksCache(environmentService, j));
    this.h.registerParticipant({
      postInstall: async (extension) => {
        return this.m(extension);
      },
      postUninstall: async (extension) => {
        return this.n(extension);
      }
    });
  }
  async getBuiltInExtensionTranslationsUri(id2, language) {
    const packs = await this.g.getLanguagePacks();
    const pack = packs[language];
    if (!pack) {
      this.j.warn(`No language pack found for ${language}`);
      return void 0;
    }
    const translation = pack.translations[id2];
    return translation ? URI.file(translation) : void 0;
  }
  async getInstalledLanguages() {
    const languagePacks = await this.g.getLanguagePacks();
    const languages = Object.keys(languagePacks).map((locale) => {
      const languagePack = languagePacks[locale];
      const baseQuickPick = this.f(locale, languagePack.label);
      return {
        ...baseQuickPick,
        extensionId: languagePack.extensions[0].extensionIdentifier.id
      };
    });
    languages.push(this.f("en", "English"));
    languages.sort((a, b) => a.label.localeCompare(b.label));
    return languages;
  }
  async m(extension) {
    if (extension && extension.manifest && extension.manifest.contributes && extension.manifest.contributes.localizations && extension.manifest.contributes.localizations.length) {
      this.j.info("Adding language packs from the extension", extension.identifier.id);
      await this.update();
    }
  }
  async n(extension) {
    const languagePacks = await this.g.getLanguagePacks();
    if (Object.keys(languagePacks).some((language) => languagePacks[language] && languagePacks[language].extensions.some((e) => $8p(e.extensionIdentifier, extension.identifier)))) {
      this.j.info("Removing language packs from the extension", extension.identifier.id);
      await this.update();
    }
  }
  async update() {
    const [current, installed] = await Promise.all([this.g.getLanguagePacks(), this.h.getInstalled()]);
    const updated = await this.g.update(installed);
    return !$Hb(Object.keys(current), Object.keys(updated));
  }
};
$xs = __decorate([
  __param(0, $Jp),
  __param(1, $8i),
  __param(2, $Gp),
  __param(3, $uk)
], $xs);
var LanguagePacksCache = class LanguagePacksCache2 extends $0c {
  constructor(environmentService, j) {
    super();
    this.j = j;
    this.c = {};
    this.f = $vc(environmentService.userDataPath, "languagepacks.json");
    this.g = new $7h();
  }
  getLanguagePacks() {
    if (this.g.size || !this.h) {
      return this.s().then(() => this.c);
    }
    return Promise.resolve(this.c);
  }
  update(extensions) {
    return this.s((languagePacks) => {
      Object.keys(languagePacks).forEach((language) => delete languagePacks[language]);
      this.m(languagePacks, ...extensions);
    }).then(() => this.c);
  }
  m(languagePacks, ...extensions) {
    for (const extension of extensions) {
      if (extension && extension.manifest && extension.manifest.contributes && extension.manifest.contributes.localizations && extension.manifest.contributes.localizations.length) {
        this.n(languagePacks, extension);
      }
    }
    Object.keys(languagePacks).forEach((languageId) => this.r(languagePacks[languageId]));
  }
  n(languagePacks, extension) {
    const extensionIdentifier = extension.identifier;
    const localizations = extension.manifest.contributes && extension.manifest.contributes.localizations ? extension.manifest.contributes.localizations : [];
    for (const localizationContribution of localizations) {
      if (extension.location.scheme === Schemas.file && isValidLocalization(localizationContribution)) {
        let languagePack = languagePacks[localizationContribution.languageId];
        if (!languagePack) {
          languagePack = {
            hash: "",
            extensions: [],
            translations: {},
            label: localizationContribution.localizedLanguageName ?? localizationContribution.languageName
          };
          languagePacks[localizationContribution.languageId] = languagePack;
        }
        const extensionInLanguagePack = languagePack.extensions.filter((e) => $8p(e.extensionIdentifier, extensionIdentifier))[0];
        if (extensionInLanguagePack) {
          extensionInLanguagePack.version = extension.manifest.version;
        } else {
          languagePack.extensions.push({ extensionIdentifier, version: extension.manifest.version });
        }
        for (const translation of localizationContribution.translations) {
          languagePack.translations[translation.id] = $vc(extension.location.fsPath, translation.path);
        }
      }
    }
  }
  r(languagePack) {
    if (languagePack) {
      const md5 = createHash3("md5");
      for (const extension of languagePack.extensions) {
        md5.update(extension.extensionIdentifier.uuid || extension.extensionIdentifier.id).update(extension.version);
      }
      languagePack.hash = md5.digest("hex");
    }
  }
  s(fn = () => null) {
    return this.g.queue(() => {
      let result = null;
      return fs7.promises.readFile(this.f, "utf8").then(void 0, (err) => err.code === "ENOENT" ? Promise.resolve("{}") : Promise.reject(err)).then((raw) => {
        try {
          return JSON.parse(raw);
        } catch (e) {
          return {};
        }
      }).then((languagePacks) => {
        result = fn(languagePacks);
        return languagePacks;
      }).then((languagePacks) => {
        for (const language of Object.keys(languagePacks)) {
          if (!languagePacks[language]) {
            delete languagePacks[language];
          }
        }
        this.c = languagePacks;
        this.h = true;
        const raw = JSON.stringify(this.c);
        this.j.debug("Writing language packs", raw);
        return Promises2.writeFile(this.f, raw);
      }).then(() => result, (error) => this.j.error(error));
    });
  }
};
LanguagePacksCache = __decorate([
  __param(0, $8i),
  __param(1, $uk)
], LanguagePacksCache);
function isValidLocalization(localization) {
  if (typeof localization.languageId !== "string") {
    return false;
  }
  if (!Array.isArray(localization.translations) || localization.translations.length === 0) {
    return false;
  }
  for (const translation of localization.translations) {
    if (typeof translation.id !== "string") {
      return false;
    }
    if (typeof translation.path !== "string") {
      return false;
    }
  }
  if (localization.languageName && typeof localization.languageName !== "string") {
    return false;
  }
  if (localization.localizedLanguageName && typeof localization.localizedLanguageName !== "string") {
    return false;
  }
  return true;
}

// out-build/vs/platform/log/common/logIpc.js
var $Ps = class extends $Fk {
  constructor(r, logLevel, logsHome, loggers, t) {
    super(logLevel, logsHome, loggers);
    this.r = r;
    this.t = t;
    this.B(t.listen("onDidChangeLogLevel", r)((arg) => {
      if ($wk(arg)) {
        super.setLogLevel(arg);
      } else {
        super.setLogLevel(URI.revive(arg[0]), arg[1]);
      }
    }));
    this.B(t.listen("onDidChangeVisibility", r)(([resource, visibility]) => super.setVisibility(URI.revive(resource), visibility)));
    this.B(t.listen("onDidChangeLoggers", r)(({ added, removed }) => {
      for (const loggerResource of added) {
        super.registerLogger({ ...loggerResource, resource: URI.revive(loggerResource.resource) });
      }
      for (const loggerResource of removed) {
        super.deregisterLogger(loggerResource.resource);
      }
    }));
  }
  createConsoleMainLogger() {
    return new $Dk({
      log: (level, args) => {
        this.t.call("consoleLog", [level, args]);
      }
    });
  }
  registerLogger(logger) {
    super.registerLogger(logger);
    this.t.call("registerLogger", [logger, this.r]);
  }
  deregisterLogger(resource) {
    super.deregisterLogger(resource);
    this.t.call("deregisterLogger", [resource, this.r]);
  }
  setLogLevel(arg1, arg2) {
    super.setLogLevel(arg1, arg2);
    this.t.call("setLogLevel", [arg1, arg2]);
  }
  setVisibility(resourceOrId, visibility) {
    super.setVisibility(resourceOrId, visibility);
    this.t.call("setVisibility", [this.n(resourceOrId), visibility]);
  }
  s(file, logLevel, options) {
    return new Logger(this.t, file, logLevel, options, this.r);
  }
  static setLogLevel(channel, arg1, arg2) {
    return channel.call("setLogLevel", [arg1, arg2]);
  }
};
var Logger = class extends $Ak {
  constructor(r, s, logLevel, loggerOptions, windowId) {
    super(loggerOptions?.logLevel === "always");
    this.r = r;
    this.s = s;
    this.m = false;
    this.n = [];
    this.setLevel(logLevel);
    this.r.call("createLogger", [s, loggerOptions, windowId]).then(() => {
      this.u(this.n);
      this.m = true;
    });
  }
  g(level, message) {
    const messages = [[level, message]];
    if (this.m) {
      this.u(messages);
    } else {
      this.n.push(...messages);
    }
  }
  u(messages) {
    this.r.call("log", [this.s, messages]);
  }
};

// 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/telemetry/common/telemetryIpc.js
var $Zkc = class {
  constructor(b) {
    this.b = b;
  }
  listen(_, event) {
    throw new Error(`Event not found: ${event}`);
  }
  call(_, command, { eventName, data }) {
    this.b.forEach((a) => a.log(eventName, data));
    return Promise.resolve(null);
  }
};
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/telemetryLogAppender.js
var $bic = class $bic2 extends $0c {
  constructor(logService, loggerService, environmentService, productService, b = "") {
    super();
    this.b = b;
    const logger = loggerService.getLogger($Wp);
    if (logger) {
      this.a = this.B(logger);
    } else {
      const justLoggingAndNotSending = $1p(productService, environmentService);
      const logSuffix = justLoggingAndNotSending ? " (Not Sent)" : "";
      const isVisible = () => $Zp(productService, environmentService) && logService.getLevel() === LogLevel.Trace;
      this.a = this.B(loggerService.createLogger($Wp, { name: localize(2081, null, logSuffix), hidden: !isVisible() }));
      this.B(logService.onDidChangeLogLevel(() => loggerService.setVisibility($Wp, isVisible())));
      this.a.info("Below are logs for every telemetry event sent from VS Code once the log level is set to trace.");
      this.a.info("===========================================================");
    }
  }
  flush() {
    return Promise.resolve();
  }
  log(eventName, data) {
    this.a.trace(`${this.b}telemetry/${eventName}`, $3p(data));
  }
};
$bic = __decorate([
  __param(0, $uk),
  __param(1, $vk),
  __param(2, $7i),
  __param(3, $Nk)
], $bic);

// 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/telemetry/node/customEndpointTelemetryService.js
var $dmc = class $dmc2 {
  constructor(b, c, d, e, f, g) {
    this.b = b;
    this.c = c;
    this.d = d;
    this.e = e;
    this.f = f;
    this.g = g;
    this.a = /* @__PURE__ */ new Map();
  }
  h(endpoint) {
    if (!this.a.has(endpoint.id)) {
      const telemetryInfo = /* @__PURE__ */ Object.create(null);
      telemetryInfo["common.vscodemachineid"] = this.c.machineId;
      telemetryInfo["common.vscodesessionid"] = this.c.sessionId;
      const args = [endpoint.id, JSON.stringify(telemetryInfo), endpoint.aiKey];
      const client = new $Er($hh.asFileUri("bootstrap-fork").fsPath, {
        serverName: "Debug Telemetry",
        timeout: 1e3 * 60 * 5,
        args,
        env: {
          ELECTRON_RUN_AS_NODE: 1,
          VSCODE_PIPE_LOGGING: "true",
          VSCODE_AMD_ENTRYPOINT: "vs/workbench/contrib/debug/node/telemetryApp"
        }
      });
      const channel = client.getChannel("telemetryAppender");
      const appenders = [
        new $1kc(channel),
        new $bic(this.d, this.e, this.f, this.g, `[${endpoint.id}] `)
      ];
      this.a.set(endpoint.id, new $Ds({
        appenders,
        sendErrorTelemetry: endpoint.sendErrorTelemetry
      }, this.b, this.g));
    }
    return this.a.get(endpoint.id);
  }
  publicLog(telemetryEndpoint, eventName, data) {
    const customTelemetryService = this.h(telemetryEndpoint);
    customTelemetryService.publicLog(eventName, data);
  }
  publicLogError(telemetryEndpoint, errorEventName, data) {
    const customTelemetryService = this.h(telemetryEndpoint);
    customTelemetryService.publicLogError(errorEventName, data);
  }
};
$dmc = __decorate([
  __param(0, $tj),
  __param(1, $tm),
  __param(2, $uk),
  __param(3, $vk),
  __param(4, $7i),
  __param(5, $Nk)
], $dmc);

// out-build/vs/platform/extensionManagement/common/extensionStorage.js
var $Zw_1;
var $Yw = $Zi("IExtensionStorageService");
var EXTENSION_KEYS_ID_VERSION_REGEX = /^extensionKeys\/([^.]+\..+)@(\d+\.\d+\.\d+(-.*)?)$/;
var $Zw = class $Zw2 extends $0c {
  static {
    $Zw_1 = this;
  }
  static {
    this.a = 512 * 1024;
  }
  static b(extension) {
    return `extensionKeys/${$_p(extension.id)}@${extension.version}`;
  }
  static c(key) {
    const matches = EXTENSION_KEYS_ID_VERSION_REGEX.exec(key);
    if (matches && matches[1]) {
      return { id: matches[1], version: matches[2] };
    }
    return void 0;
  }
  /* TODO @sandy081: This has to be done across all profiles */
  static async removeOutdatedExtensionVersions(extensionManagementService, storageService) {
    const extensions = await extensionManagementService.getInstalled();
    const extensionVersionsToRemove = [];
    for (const [id2, versions] of $Zw_1.f(storageService)) {
      const extensionVersion = extensions.find((e) => $8p(e.identifier, { id: id2 }))?.manifest.version;
      for (const version of versions) {
        if (extensionVersion !== version) {
          extensionVersionsToRemove.push($Zw_1.b({ id: id2, version }));
        }
      }
    }
    for (const key of extensionVersionsToRemove) {
      storageService.remove(
        key,
        0
        /* StorageScope.PROFILE */
      );
    }
  }
  static f(storageService) {
    const extensionsWithKeysForSync = /* @__PURE__ */ new Map();
    const keys = storageService.keys(
      0,
      1
      /* StorageTarget.MACHINE */
    );
    for (const key of keys) {
      const extensionIdWithVersion = $Zw_1.c(key);
      if (extensionIdWithVersion) {
        let versions = extensionsWithKeysForSync.get(extensionIdWithVersion.id.toLowerCase());
        if (!versions) {
          extensionsWithKeysForSync.set(extensionIdWithVersion.id.toLowerCase(), versions = []);
        }
        versions.push(extensionIdWithVersion.version);
      }
    }
    return extensionsWithKeysForSync;
  }
  constructor(j, m, n) {
    super();
    this.j = j;
    this.m = m;
    this.n = n;
    this.g = this.B(new $De());
    this.onDidChangeExtensionStorageToSync = this.g.event;
    this.h = $Zw_1.f(j);
    this.B(this.j.onDidChangeValue(0, void 0, this.B(new $9c()))((e) => this.r(e)));
  }
  r(e) {
    if (this.h.has(e.key.toLowerCase())) {
      this.g.fire();
      return;
    }
    const extensionIdWithVersion = $Zw_1.c(e.key);
    if (extensionIdWithVersion) {
      if (this.j.get(
        e.key,
        0
        /* StorageScope.PROFILE */
      ) === void 0) {
        this.h.delete(extensionIdWithVersion.id.toLowerCase());
      } else {
        let versions = this.h.get(extensionIdWithVersion.id.toLowerCase());
        if (!versions) {
          this.h.set(extensionIdWithVersion.id.toLowerCase(), versions = []);
        }
        versions.push(extensionIdWithVersion.version);
        this.g.fire();
      }
      return;
    }
  }
  s(extension) {
    if ($yg(extension)) {
      return extension;
    }
    const publisher = extension.manifest ? extension.manifest.publisher : extension.publisher;
    const name = extension.manifest ? extension.manifest.name : extension.name;
    return $$p(publisher, name);
  }
  getExtensionState(extension, global2) {
    const extensionId = this.s(extension);
    const jsonValue = this.getExtensionStateRaw(extension, global2);
    if (jsonValue) {
      try {
        return JSON.parse(jsonValue);
      } catch (error) {
        this.n.error(`[mainThreadStorage] unexpected error parsing storage contents (extensionId: ${extensionId}, global: ${global2}): ${error}`);
      }
    }
    return void 0;
  }
  getExtensionStateRaw(extension, global2) {
    const extensionId = this.s(extension);
    const rawState = this.j.get(
      extensionId,
      global2 ? 0 : 1
      /* StorageScope.WORKSPACE */
    );
    if (rawState && rawState?.length > $Zw_1.a) {
      this.n.warn(`[mainThreadStorage] large extension state detected (extensionId: ${extensionId}, global: ${global2}): ${rawState.length / 1024}kb. Consider to use 'storageUri' or 'globalStorageUri' to store this data on disk instead.`);
    }
    return rawState;
  }
  setExtensionState(extension, state, global2) {
    const extensionId = this.s(extension);
    if (state === void 0) {
      this.j.remove(
        extensionId,
        global2 ? 0 : 1
        /* StorageScope.WORKSPACE */
      );
    } else {
      this.j.store(
        extensionId,
        JSON.stringify(state),
        global2 ? 0 : 1,
        1
        /* StorageTarget.MACHINE */
      );
    }
  }
  setKeysForSync(extensionIdWithVersion, keys) {
    this.j.store(
      $Zw_1.b(extensionIdWithVersion),
      JSON.stringify(keys),
      0,
      1
      /* StorageTarget.MACHINE */
    );
  }
  getKeysForSync(extensionIdWithVersion) {
    const extensionKeysForSyncFromProduct = this.m.extensionSyncedKeys?.[extensionIdWithVersion.id.toLowerCase()];
    const extensionKeysForSyncFromStorageValue = this.j.get(
      $Zw_1.b(extensionIdWithVersion),
      0
      /* StorageScope.PROFILE */
    );
    const extensionKeysForSyncFromStorage = extensionKeysForSyncFromStorageValue ? JSON.parse(extensionKeysForSyncFromStorageValue) : void 0;
    return extensionKeysForSyncFromStorage && extensionKeysForSyncFromProduct ? $Zb([...extensionKeysForSyncFromStorage, ...extensionKeysForSyncFromProduct]) : extensionKeysForSyncFromStorage || extensionKeysForSyncFromProduct;
  }
  addToMigrationList(from, to) {
    if (from !== to) {
      const migrationList = this.t.filter((entry) => !entry.includes(from) && !entry.includes(to));
      migrationList.push([from, to]);
      this.t = migrationList;
    }
  }
  getSourceExtensionToMigrate(toExtensionId) {
    const entry = this.t.find(([, to]) => toExtensionId === to);
    return entry ? entry[0] : void 0;
  }
  get t() {
    const value = this.j.get("extensionStorage.migrationList", -1, "[]");
    try {
      const migrationList = JSON.parse(value);
      if (Array.isArray(migrationList)) {
        return migrationList;
      }
    } catch (error) {
    }
    return [];
  }
  set t(migrationList) {
    if (migrationList.length) {
      this.j.store(
        "extensionStorage.migrationList",
        JSON.stringify(migrationList),
        -1,
        1
        /* StorageTarget.MACHINE */
      );
    } else {
      this.j.remove(
        "extensionStorage.migrationList",
        -1
        /* StorageScope.APPLICATION */
      );
    }
  }
};
$Zw = $Zw_1 = __decorate([
  __param(0, $Dq),
  __param(1, $Nk),
  __param(2, $uk)
], $Zw);

// out-build/vs/platform/userDataSync/common/ignoredExtensions.js
var $aUb = $Zi("IIgnoredExtensionsManagementService");
var $bUb = class $bUb2 {
  constructor(a) {
    this.a = a;
  }
  hasToNeverSyncExtension(extensionId) {
    const configuredIgnoredExtensions = this.b();
    return configuredIgnoredExtensions.includes(extensionId.toLowerCase());
  }
  hasToAlwaysSyncExtension(extensionId) {
    const configuredIgnoredExtensions = this.b();
    return configuredIgnoredExtensions.includes(`-${extensionId.toLowerCase()}`);
  }
  updateIgnoredExtensions(ignoredExtensionId, ignore) {
    let currentValue = [...this.a.getValue("settingsSync.ignoredExtensions")].map((id2) => id2.toLowerCase());
    currentValue = currentValue.filter((v) => v !== ignoredExtensionId && v !== `-${ignoredExtensionId}`);
    if (ignore) {
      currentValue.push(ignoredExtensionId.toLowerCase());
    }
    return this.a.updateValue(
      "settingsSync.ignoredExtensions",
      currentValue.length ? currentValue : void 0,
      2
      /* ConfigurationTarget.USER */
    );
  }
  updateSynchronizedExtensions(extensionId, sync) {
    let currentValue = [...this.a.getValue("settingsSync.ignoredExtensions")].map((id2) => id2.toLowerCase());
    currentValue = currentValue.filter((v) => v !== extensionId && v !== `-${extensionId}`);
    if (sync) {
      currentValue.push(`-${extensionId.toLowerCase()}`);
    }
    return this.a.updateValue(
      "settingsSync.ignoredExtensions",
      currentValue.length ? currentValue : void 0,
      2
      /* ConfigurationTarget.USER */
    );
  }
  getIgnoredExtensions(installed) {
    const defaultIgnoredExtensions = installed.filter((i) => i.isMachineScoped).map((i) => i.identifier.id.toLowerCase());
    const value = this.b().map((id2) => id2.toLowerCase());
    const added = [], removed = [];
    if (Array.isArray(value)) {
      for (const key of value) {
        if (key.startsWith("-")) {
          removed.push(key.substring(1));
        } else {
          added.push(key);
        }
      }
    }
    return $Zb([...defaultIgnoredExtensions, ...added].filter((setting) => !removed.includes(setting)));
  }
  b() {
    let userValue = this.a.inspect("settingsSync.ignoredExtensions").userValue;
    if (userValue !== void 0) {
      return userValue;
    }
    userValue = this.a.inspect("sync.ignoredExtensions").userValue;
    if (userValue !== void 0) {
      return userValue;
    }
    return (this.a.getValue("settingsSync.ignoredExtensions") || []).map((id2) => id2.toLowerCase());
  }
};
$bUb = __decorate([
  __param(0, $tj)
], $bUb);

// out-build/vs/platform/userDataSync/common/userDataSync.js
function $Brb() {
  const allSettings = $Mo.as($Ro.Configuration).getConfigurationProperties();
  return Object.keys(allSettings).filter((setting) => !!allSettings[setting].disallowSyncIgnore);
}
function $Crb(excludeExtensions = false) {
  const allSettings = $Mo.as($Ro.Configuration).getConfigurationProperties();
  const ignoredSettings = getIgnoredSettings(allSettings, excludeExtensions);
  const disallowedSettings = $Brb();
  return $Zb([...ignoredSettings, ...disallowedSettings]);
}
function $Drb(manifest) {
  if (!manifest.contributes?.configuration) {
    return [];
  }
  const configurations = Array.isArray(manifest.contributes.configuration) ? manifest.contributes.configuration : [manifest.contributes.configuration];
  if (!configurations.length) {
    return [];
  }
  const properties = $8o(configurations);
  return getIgnoredSettings(properties, false);
}
function getIgnoredSettings(properties, excludeExtensions) {
  const ignoredSettings = /* @__PURE__ */ new Set();
  for (const key in properties) {
    if (excludeExtensions && !!properties[key].source) {
      continue;
    }
    const scope = $yg(properties[key].scope) ? $9o(properties[key].scope) : properties[key].scope;
    if (properties[key].ignoreSync || scope === 2 || scope === 6) {
      ignoredSettings.add(key);
    }
  }
  return [...ignoredSettings.values()];
}
var $Erb = "settingsSync";
var $Frb = "settingsSync.keybindingsPerPlatform";
function $Grb() {
  const ignoredSettingsSchemaId = "vscode://schemas/ignoredSettings";
  const configurationRegistry2 = $Mo.as($Ro.Configuration);
  configurationRegistry2.registerConfiguration({
    id: "settingsSync",
    order: 30,
    title: localize(2469, null),
    type: "object",
    properties: {
      [$Frb]: {
        type: "boolean",
        description: localize(2470, null),
        default: true,
        scope: 1,
        tags: ["sync", "usesOnlineServices"]
      },
      "settingsSync.ignoredExtensions": {
        "type": "array",
        markdownDescription: localize(2471, null),
        items: [{
          type: "string",
          pattern: $tp,
          errorMessage: localize(2472, null)
        }],
        "default": [],
        "scope": 1,
        uniqueItems: true,
        disallowSyncIgnore: true,
        tags: ["sync", "usesOnlineServices"]
      },
      "settingsSync.ignoredSettings": {
        "type": "array",
        description: localize(2473, null),
        "default": [],
        "scope": 1,
        $ref: ignoredSettingsSchemaId,
        additionalProperties: true,
        uniqueItems: true,
        disallowSyncIgnore: true,
        tags: ["sync", "usesOnlineServices"]
      }
    }
  });
  const jsonRegistry = $Mo.as($No.JSONContribution);
  const registerIgnoredSettingsSchema = () => {
    const disallowedIgnoredSettings = $Brb();
    const defaultIgnoredSettings = $Crb();
    const settings = Object.keys($So.properties).filter((setting) => !defaultIgnoredSettings.includes(setting));
    const ignoredSettings = defaultIgnoredSettings.filter((setting) => !disallowedIgnoredSettings.includes(setting));
    const ignoredSettingsSchema = {
      items: {
        type: "string",
        enum: [...settings, ...ignoredSettings.map((setting) => `-${setting}`)]
      }
    };
    jsonRegistry.registerSchema(ignoredSettingsSchemaId, ignoredSettingsSchema);
  };
  return configurationRegistry2.onDidUpdateConfiguration(() => registerIgnoredSettingsSchema());
}
var SyncResource;
(function(SyncResource2) {
  SyncResource2["Settings"] = "settings";
  SyncResource2["Keybindings"] = "keybindings";
  SyncResource2["Snippets"] = "snippets";
  SyncResource2["Tasks"] = "tasks";
  SyncResource2["Extensions"] = "extensions";
  SyncResource2["GlobalState"] = "globalState";
  SyncResource2["Profiles"] = "profiles";
  SyncResource2["WorkspaceState"] = "workspaceState";
})(SyncResource || (SyncResource = {}));
var $Irb = [
  "settings",
  "keybindings",
  "snippets",
  "tasks",
  "extensions",
  "globalState",
  "profiles"
  /* SyncResource.Profiles */
];
function $Jrb(collection, ...paths) {
  return collection ? [collection, ...paths] : paths;
}
function $Krb(collection, syncResource, environmentService, extUri) {
  return extUri.joinPath(environmentService.userDataSyncHome, ...$Jrb(collection, syncResource, `lastSync${syncResource}.json`));
}
var $Lrb = $Zi("IUserDataSyncStoreManagementService");
var $Mrb = $Zi("IUserDataSyncStoreService");
var $Nrb = $Zi("IUserDataSyncLocalStoreService");
var $Orb = "x-operation-id";
var $Prb = "X-Execution-Id";
function $Qrb(executionId) {
  const headers = {};
  headers[$Prb] = executionId;
  return headers;
}
var UserDataSyncErrorCode;
(function(UserDataSyncErrorCode2) {
  UserDataSyncErrorCode2["Unauthorized"] = "Unauthorized";
  UserDataSyncErrorCode2["Forbidden"] = "Forbidden";
  UserDataSyncErrorCode2["NotFound"] = "NotFound";
  UserDataSyncErrorCode2["MethodNotFound"] = "MethodNotFound";
  UserDataSyncErrorCode2["Conflict"] = "Conflict";
  UserDataSyncErrorCode2["Gone"] = "Gone";
  UserDataSyncErrorCode2["PreconditionFailed"] = "PreconditionFailed";
  UserDataSyncErrorCode2["TooLarge"] = "TooLarge";
  UserDataSyncErrorCode2["UpgradeRequired"] = "UpgradeRequired";
  UserDataSyncErrorCode2["PreconditionRequired"] = "PreconditionRequired";
  UserDataSyncErrorCode2["TooManyRequests"] = "RemoteTooManyRequests";
  UserDataSyncErrorCode2["TooManyRequestsAndRetryAfter"] = "TooManyRequestsAndRetryAfter";
  UserDataSyncErrorCode2["RequestFailed"] = "RequestFailed";
  UserDataSyncErrorCode2["RequestCanceled"] = "RequestCanceled";
  UserDataSyncErrorCode2["RequestTimeout"] = "RequestTimeout";
  UserDataSyncErrorCode2["RequestProtocolNotSupported"] = "RequestProtocolNotSupported";
  UserDataSyncErrorCode2["RequestPathNotEscaped"] = "RequestPathNotEscaped";
  UserDataSyncErrorCode2["RequestHeadersNotObject"] = "RequestHeadersNotObject";
  UserDataSyncErrorCode2["NoCollection"] = "NoCollection";
  UserDataSyncErrorCode2["NoRef"] = "NoRef";
  UserDataSyncErrorCode2["EmptyResponse"] = "EmptyResponse";
  UserDataSyncErrorCode2["TurnedOff"] = "TurnedOff";
  UserDataSyncErrorCode2["SessionExpired"] = "SessionExpired";
  UserDataSyncErrorCode2["ServiceChanged"] = "ServiceChanged";
  UserDataSyncErrorCode2["DefaultServiceChanged"] = "DefaultServiceChanged";
  UserDataSyncErrorCode2["LocalTooManyProfiles"] = "LocalTooManyProfiles";
  UserDataSyncErrorCode2["LocalTooManyRequests"] = "LocalTooManyRequests";
  UserDataSyncErrorCode2["LocalPreconditionFailed"] = "LocalPreconditionFailed";
  UserDataSyncErrorCode2["LocalInvalidContent"] = "LocalInvalidContent";
  UserDataSyncErrorCode2["LocalError"] = "LocalError";
  UserDataSyncErrorCode2["IncompatibleLocalContent"] = "IncompatibleLocalContent";
  UserDataSyncErrorCode2["IncompatibleRemoteContent"] = "IncompatibleRemoteContent";
  UserDataSyncErrorCode2["Unknown"] = "Unknown";
})(UserDataSyncErrorCode || (UserDataSyncErrorCode = {}));
var $Rrb = class extends Error {
  constructor(message, code, resource, operationId) {
    super(message);
    this.code = code;
    this.resource = resource;
    this.operationId = operationId;
    this.name = `${this.code} (UserDataSyncError) syncResource:${this.resource || "unknown"} operationId:${this.operationId || "unknown"}`;
  }
};
var $Srb = class extends $Rrb {
  constructor(message, url, code, serverCode, operationId) {
    super(message, code, void 0, operationId);
    this.url = url;
    this.serverCode = serverCode;
  }
};
var $Trb = class extends $Rrb {
  constructor(message, code) {
    super(message, code);
  }
};
(function($Rrb2) {
  function toUserDataSyncError(error) {
    if (error instanceof $Rrb2) {
      return error;
    }
    const match = /^(.+) \(UserDataSyncError\) syncResource:(.+) operationId:(.+)$/.exec(error.name);
    if (match && match[1]) {
      const syncResource = match[2] === "unknown" ? void 0 : match[2];
      const operationId = match[3] === "unknown" ? void 0 : match[3];
      return new $Rrb2(error.message, match[1], syncResource, operationId);
    }
    return new $Rrb2(
      error.message,
      "Unknown"
      /* UserDataSyncErrorCode.Unknown */
    );
  }
  $Rrb2.toUserDataSyncError = toUserDataSyncError;
})($Rrb || ($Rrb = {}));
var SyncStatus;
(function(SyncStatus2) {
  SyncStatus2["Uninitialized"] = "uninitialized";
  SyncStatus2["Idle"] = "idle";
  SyncStatus2["Syncing"] = "syncing";
  SyncStatus2["HasConflicts"] = "hasConflicts";
})(SyncStatus || (SyncStatus = {}));
var Change;
(function(Change2) {
  Change2[Change2["None"] = 0] = "None";
  Change2[Change2["Added"] = 1] = "Added";
  Change2[Change2["Modified"] = 2] = "Modified";
  Change2[Change2["Deleted"] = 3] = "Deleted";
})(Change || (Change = {}));
var MergeState;
(function(MergeState2) {
  MergeState2["Preview"] = "preview";
  MergeState2["Conflict"] = "conflict";
  MergeState2["Accepted"] = "accepted";
})(MergeState || (MergeState = {}));
var $Urb = "sync.store.url.type";
function $Vrb(resource) {
  return `sync.enable.${resource}`;
}
var $Wrb = $Zi("IUserDataSyncEnablementService");
var $Xrb = $Zi("IUserDataSyncService");
var $Yrb = $Zi("IUserDataSyncResourceProviderService");
var $Zrb = $Zi("IUserDataAutoSyncService");
var $1rb = $Zi("IUserDataSyncUtilService");
var $2rb = $Zi("IUserDataSyncLogService");
var $3rb = "userDataSync";
var $4rb = "vscode-userdata-sync";
var $5rb = "preview";

// out-build/vs/platform/userDataSync/common/userDataSyncAccount.js
var $GRb = $Zi("IUserDataSyncAccountService");
var $HRb = class $HRb2 extends $0c {
  get account() {
    return this.a;
  }
  constructor(g, h) {
    super();
    this.g = g;
    this.h = h;
    this.b = this.B(new $De());
    this.onDidChangeAccount = this.b.event;
    this.c = this.B(new $De());
    this.onTokenFailed = this.c.event;
    this.f = false;
    this.B(g.onTokenFailed((code) => {
      this.h.info("Settings Sync auth token failed", this.account?.authenticationProviderId, this.f, code);
      this.updateAccount(void 0);
      if (code === "Forbidden") {
        this.c.fire(
          true
          /*bail out immediately*/
        );
      } else {
        this.c.fire(
          this.f
          /* bail out if token failed before */
        );
      }
      this.f = true;
    }));
    this.B(g.onTokenSucceed(() => this.f = false));
  }
  async updateAccount(account) {
    if (account && this.a ? account.token !== this.a.token || account.authenticationProviderId !== this.a.authenticationProviderId : account !== this.a) {
      this.a = account;
      if (this.a) {
        this.g.setAuthToken(this.a.token, this.a.authenticationProviderId);
      }
      this.b.fire(account);
    }
  }
};
$HRb = __decorate([
  __param(0, $Mrb),
  __param(1, $2rb)
], $HRb);

// 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/userDataSync/common/userDataSyncLocalStoreService.js
var $Qic = class $Qic2 extends $0c {
  constructor(a, b, c, f, g) {
    super();
    this.a = a;
    this.b = b;
    this.c = c;
    this.f = f;
    this.g = g;
    this.h();
  }
  async h() {
    for (const profile of this.g.profiles) {
      for (const resource of $Irb) {
        try {
          await this.m(this.j(resource, profile.isDefault ? void 0 : profile.id));
        } catch (error) {
          this.f.error(error);
        }
      }
    }
    let stat;
    try {
      stat = await this.b.resolve(this.a.userDataSyncHome);
    } catch (error) {
      if ($Ll(error) !== 1) {
        this.f.error(error);
      }
      return;
    }
    if (stat.children) {
      for (const child of stat.children) {
        if (child.isDirectory && !$Irb.includes(child.name) && !this.g.profiles.some((profile) => profile.id === child.name)) {
          try {
            this.f.info("Deleting non existing profile from backup", child.resource.path);
            await this.b.del(child.resource, { recursive: true });
          } catch (error) {
            this.f.error(error);
          }
        }
      }
    }
  }
  async getAllResourceRefs(resource, collection, root) {
    const folder = this.j(resource, collection, root);
    try {
      const stat = await this.b.resolve(folder);
      if (stat.children) {
        const all = stat.children.filter((stat2) => stat2.isFile && !stat2.name.startsWith("lastSync")).sort().reverse();
        return all.map((stat2) => ({
          ref: stat2.name,
          created: this.n(stat2)
        }));
      }
    } catch (error) {
      if ($Ll(error) !== 1) {
        throw error;
      }
    }
    return [];
  }
  async resolveResourceContent(resourceKey, ref, collection, root) {
    const folder = this.j(resourceKey, collection, root);
    const file = $Ah(folder, ref);
    try {
      const content = await this.b.readFile(file);
      return content.value.toString();
    } catch (error) {
      this.f.error(error);
      return null;
    }
  }
  async writeResource(resourceKey, content, cTime, collection, root) {
    const folder = this.j(resourceKey, collection, root);
    const resource = $Ah(folder, `${$mn(cTime).replace(/-|:|\.\d+Z$/g, "")}.json`);
    try {
      await this.b.writeFile(resource, $7e.fromString(content));
    } catch (e) {
      this.f.error(e);
    }
  }
  j(resource, collection, root = this.a.userDataSyncHome) {
    return $Ah(root, ...collection ? [collection, resource] : [resource]);
  }
  async m(folder) {
    try {
      try {
        if (!await this.b.exists(folder)) {
          return;
        }
      } catch (e) {
        return;
      }
      const stat = await this.b.resolve(folder);
      if (stat.children) {
        const all = stat.children.filter((stat2) => stat2.isFile && /^\d{8}T\d{6}(\.json)?$/.test(stat2.name)).sort();
        const backUpMaxAge = 1e3 * 60 * 60 * 24 * (this.c.getValue("sync.localBackupDuration") || 30);
        let toDelete = all.filter((stat2) => Date.now() - this.n(stat2) > backUpMaxAge);
        const remaining = all.length - toDelete.length;
        if (remaining < 10) {
          toDelete = toDelete.slice(10 - remaining);
        }
        await Promises.settled(toDelete.map(async (stat2) => {
          this.f.info("Deleting from backup", stat2.resource.path);
          await this.b.del(stat2.resource);
        }));
      }
    } catch (e) {
      this.f.error(e);
    }
  }
  n(stat) {
    return new Date(parseInt(stat.name.substring(0, 4)), parseInt(stat.name.substring(4, 6)) - 1, parseInt(stat.name.substring(6, 8)), parseInt(stat.name.substring(9, 11)), parseInt(stat.name.substring(11, 13)), parseInt(stat.name.substring(13, 15))).getTime();
  }
};
$Qic = __decorate([
  __param(0, $7i),
  __param(1, $ul),
  __param(2, $tj),
  __param(3, $2rb),
  __param(4, $7l)
], $Qic);

// out-build/vs/base/common/mime.js
var $ut = Object.freeze({
  text: "text/plain",
  binary: "application/octet-stream",
  unknown: "application/unknown",
  markdown: "text/markdown",
  latex: "text/latex",
  uriList: "text/uri-list"
});

// out-build/vs/platform/userDataSync/common/userDataSyncStoreService.js
var CONFIGURATION_SYNC_STORE_KEY = "configurationSync.store";
var SYNC_PREVIOUS_STORE = "sync.previous.store";
var DONOT_MAKE_REQUESTS_UNTIL_KEY = "sync.donot-make-requests-until";
var USER_SESSION_ID_KEY = "sync.user-session-id";
var MACHINE_SESSION_ID_KEY = "sync.machine-session-id";
var REQUEST_SESSION_LIMIT = 100;
var REQUEST_SESSION_INTERVAL = 1e3 * 60 * 5;
var $aTb = class $aTb2 extends $0c {
  get userDataSyncStore() {
    return this.b;
  }
  get c() {
    return this.h.get(
      $Urb,
      -1
      /* StorageScope.APPLICATION */
    );
  }
  set c(type2) {
    this.h.store(
      $Urb,
      type2,
      -1,
      $r ? 0 : 1
      /* StorageTarget.MACHINE */
    );
  }
  constructor(f, g, h) {
    super();
    this.f = f;
    this.g = g;
    this.h = h;
    this.a = this.B(new $De());
    this.onDidChangeUserDataSyncStore = this.a.event;
    this.j();
    const disposable = this.B(new $9c());
    this.B(Event.filter(h.onDidChangeValue(-1, $Urb, disposable), () => this.c !== this.userDataSyncStore?.type, disposable)(() => this.j()));
  }
  j() {
    this.b = this.m(this.f[CONFIGURATION_SYNC_STORE_KEY]);
    this.a.fire();
  }
  m(configurationSyncStore) {
    if (!configurationSyncStore) {
      return void 0;
    }
    configurationSyncStore = $r && configurationSyncStore.web ? { ...configurationSyncStore, ...configurationSyncStore.web } : configurationSyncStore;
    if ($yg(configurationSyncStore.url) && $Ag(configurationSyncStore.authenticationProviders) && Object.keys(configurationSyncStore.authenticationProviders).every((authenticationProviderId) => Array.isArray(configurationSyncStore.authenticationProviders[authenticationProviderId].scopes))) {
      const syncStore = configurationSyncStore;
      const canSwitch = !!syncStore.canSwitch;
      const defaultType = syncStore.url === syncStore.insidersUrl ? "insiders" : "stable";
      const type2 = (canSwitch ? this.c : void 0) || defaultType;
      const url = type2 === "insiders" ? syncStore.insidersUrl : type2 === "stable" ? syncStore.stableUrl : syncStore.url;
      return {
        url: URI.parse(url),
        type: type2,
        defaultType,
        defaultUrl: URI.parse(syncStore.url),
        stableUrl: URI.parse(syncStore.stableUrl),
        insidersUrl: URI.parse(syncStore.insidersUrl),
        canSwitch,
        authenticationProviders: Object.keys(syncStore.authenticationProviders).reduce((result, id2) => {
          result.push({ id: id2, scopes: syncStore.authenticationProviders[id2].scopes });
          return result;
        }, [])
      };
    }
    return void 0;
  }
};
$aTb = __decorate([
  __param(0, $Nk),
  __param(1, $tj),
  __param(2, $Dq)
], $aTb);
var $bTb = class $bTb2 extends $aTb {
  constructor(productService, configurationService, storageService) {
    super(productService, configurationService, storageService);
    const previousConfigurationSyncStore = this.h.get(
      SYNC_PREVIOUS_STORE,
      -1
      /* StorageScope.APPLICATION */
    );
    if (previousConfigurationSyncStore) {
      this.n = JSON.parse(previousConfigurationSyncStore);
    }
    const syncStore = this.f[CONFIGURATION_SYNC_STORE_KEY];
    if (syncStore) {
      this.h.store(
        SYNC_PREVIOUS_STORE,
        JSON.stringify(syncStore),
        -1,
        1
        /* StorageTarget.MACHINE */
      );
    } else {
      this.h.remove(
        SYNC_PREVIOUS_STORE,
        -1
        /* StorageScope.APPLICATION */
      );
    }
  }
  async switch(type2) {
    if (type2 !== this.c) {
      this.c = type2;
      this.j();
    }
  }
  async getPreviousUserDataSyncStore() {
    return this.m(this.n);
  }
};
$bTb = __decorate([
  __param(0, $Nk),
  __param(1, $tj),
  __param(2, $Dq)
], $bTb);
var $cTb = class $cTb2 extends $0c {
  get donotMakeRequestsUntil() {
    return this.j;
  }
  constructor(userDataSyncStoreUrl, productService, n, r, environmentService, fileService, s) {
    super();
    this.n = n;
    this.r = r;
    this.s = s;
    this.g = this.B(new $De());
    this.onTokenFailed = this.g.event;
    this.h = this.B(new $De());
    this.onTokenSucceed = this.h.event;
    this.j = void 0;
    this.m = this.B(new $De());
    this.onDidChangeDonotMakeRequestsUntil = this.m.event;
    this.w = void 0;
    this.t(userDataSyncStoreUrl);
    this.c = $Jq(environmentService, fileService, s).then((uuid) => {
      const headers = {
        "X-Client-Name": `${productService.applicationName}${$r ? "-web" : ""}`,
        "X-Client-Version": productService.version
      };
      if (productService.commit) {
        headers["X-Client-Commit"] = productService.commit;
      }
      return headers;
    });
    this.f = new $eTb(REQUEST_SESSION_LIMIT, REQUEST_SESSION_INTERVAL, this.n, this.r);
    this.u();
    this.B($8c(() => {
      if (this.w) {
        this.w.cancel();
        this.w = void 0;
      }
    }));
  }
  setAuthToken(token, type2) {
    this.b = { token, type: type2 };
  }
  t(userDataSyncStoreUrl) {
    this.a = userDataSyncStoreUrl ? $Ah(userDataSyncStoreUrl, "v1") : void 0;
  }
  u() {
    const donotMakeRequestsUntil = this.s.getNumber(
      DONOT_MAKE_REQUESTS_UNTIL_KEY,
      -1
      /* StorageScope.APPLICATION */
    );
    if (donotMakeRequestsUntil && Date.now() < donotMakeRequestsUntil) {
      this.y(new Date(donotMakeRequestsUntil));
    }
  }
  y(donotMakeRequestsUntil) {
    if (this.j?.getTime() !== donotMakeRequestsUntil?.getTime()) {
      this.j = donotMakeRequestsUntil;
      if (this.w) {
        this.w.cancel();
        this.w = void 0;
      }
      if (this.j) {
        this.s.store(
          DONOT_MAKE_REQUESTS_UNTIL_KEY,
          this.j.getTime(),
          -1,
          1
          /* StorageTarget.MACHINE */
        );
        this.w = $Mh((token) => $1h(this.j.getTime() - Date.now(), token).then(() => this.y(void 0)));
        this.w.then(
          null,
          (e) => null
          /* ignore error */
        );
      } else {
        this.s.remove(
          DONOT_MAKE_REQUESTS_UNTIL_KEY,
          -1
          /* StorageScope.APPLICATION */
        );
      }
      this.m.fire();
    }
  }
  // #region Collection
  async getAllCollections(headers = {}) {
    if (!this.a) {
      throw new Error("No settings sync store url configured.");
    }
    const url = $Ah(this.a, "collection").toString();
    headers = { ...headers };
    headers["Content-Type"] = "application/json";
    const context = await this.D(url, { type: "GET", headers }, [], CancellationToken.None);
    return (await $wq(context))?.map(({ id: id2 }) => id2) || [];
  }
  async createCollection(headers = {}) {
    if (!this.a) {
      throw new Error("No settings sync store url configured.");
    }
    const url = $Ah(this.a, "collection").toString();
    headers = { ...headers };
    headers["Content-Type"] = $ut.text;
    const context = await this.D(url, { type: "POST", headers }, [], CancellationToken.None);
    const collectionId = await $vq(context);
    if (!collectionId) {
      throw new $Srb("Server did not return the collection id", url, "NoCollection", context.res.statusCode, context.res.headers[$Orb]);
    }
    return collectionId;
  }
  async deleteCollection(collection, headers = {}) {
    if (!this.a) {
      throw new Error("No settings sync store url configured.");
    }
    const url = collection ? $Ah(this.a, "collection", collection).toString() : $Ah(this.a, "collection").toString();
    headers = { ...headers };
    await this.D(url, { type: "DELETE", headers }, [], CancellationToken.None);
  }
  // #endregion
  // #region Resource
  async getAllResourceRefs(resource, collection) {
    if (!this.a) {
      throw new Error("No settings sync store url configured.");
    }
    const uri = this.z(this.a, collection, resource);
    const headers = {};
    const context = await this.D(uri.toString(), { type: "GET", headers }, [], CancellationToken.None);
    const result = await $wq(context) || [];
    return result.map(({ url, created }) => ({
      ref: $Ch(uri, uri.with({ path: url })),
      created: created * 1e3
      /* Server returns in seconds */
    }));
  }
  async resolveResourceContent(resource, ref, collection, headers = {}) {
    if (!this.a) {
      throw new Error("No settings sync store url configured.");
    }
    const url = $Ah(this.z(this.a, collection, resource), ref).toString();
    headers = { ...headers };
    headers["Cache-Control"] = "no-cache";
    const context = await this.D(url, { type: "GET", headers }, [], CancellationToken.None);
    const content = await $vq(context);
    return content;
  }
  async deleteResource(resource, ref, collection) {
    if (!this.a) {
      throw new Error("No settings sync store url configured.");
    }
    const url = ref !== null ? $Ah(this.z(this.a, collection, resource), ref).toString() : this.z(this.a, collection, resource).toString();
    const headers = {};
    await this.D(url, { type: "DELETE", headers }, [], CancellationToken.None);
  }
  async deleteResources() {
    if (!this.a) {
      throw new Error("No settings sync store url configured.");
    }
    const url = $Ah(this.a, "resource").toString();
    const headers = { "Content-Type": $ut.text };
    await this.D(url, { type: "DELETE", headers }, [], CancellationToken.None);
  }
  async readResource(resource, oldValue, collection, headers = {}) {
    if (!this.a) {
      throw new Error("No settings sync store url configured.");
    }
    const url = $Ah(this.z(this.a, collection, resource), "latest").toString();
    headers = { ...headers };
    headers["Cache-Control"] = "no-cache";
    if (oldValue) {
      headers["If-None-Match"] = oldValue.ref;
    }
    const context = await this.D(url, { type: "GET", headers }, [304], CancellationToken.None);
    let userData = null;
    if (context.res.statusCode === 304) {
      userData = oldValue;
    }
    if (userData === null) {
      const ref = context.res.headers["etag"];
      if (!ref) {
        throw new $Srb("Server did not return the ref", url, "NoRef", context.res.statusCode, context.res.headers[$Orb]);
      }
      const content = await $vq(context);
      if (!content && context.res.statusCode === 304) {
        throw new $Srb("Empty response", url, "EmptyResponse", context.res.statusCode, context.res.headers[$Orb]);
      }
      userData = { ref, content };
    }
    return userData;
  }
  async writeResource(resource, data, ref, collection, headers = {}) {
    if (!this.a) {
      throw new Error("No settings sync store url configured.");
    }
    const url = this.z(this.a, collection, resource).toString();
    headers = { ...headers };
    headers["Content-Type"] = $ut.text;
    if (ref) {
      headers["If-Match"] = ref;
    }
    const context = await this.D(url, { type: "POST", data, headers }, [], CancellationToken.None);
    const newRef = context.res.headers["etag"];
    if (!newRef) {
      throw new $Srb("Server did not return the ref", url, "NoRef", context.res.statusCode, context.res.headers[$Orb]);
    }
    return newRef;
  }
  // #endregion
  async manifest(oldValue, headers = {}) {
    if (!this.a) {
      throw new Error("No settings sync store url configured.");
    }
    const url = $Ah(this.a, "manifest").toString();
    headers = { ...headers };
    headers["Content-Type"] = "application/json";
    if (oldValue) {
      headers["If-None-Match"] = oldValue.ref;
    }
    const context = await this.D(url, { type: "GET", headers }, [304], CancellationToken.None);
    let manifest = null;
    if (context.res.statusCode === 304) {
      manifest = oldValue;
    }
    if (!manifest) {
      const ref = context.res.headers["etag"];
      if (!ref) {
        throw new $Srb("Server did not return the ref", url, "NoRef", context.res.statusCode, context.res.headers[$Orb]);
      }
      const content = await $vq(context);
      if (!content && context.res.statusCode === 304) {
        throw new $Srb("Empty response", url, "EmptyResponse", context.res.statusCode, context.res.headers[$Orb]);
      }
      if (content) {
        manifest = { ...JSON.parse(content), ref };
      }
    }
    const currentSessionId = this.s.get(
      USER_SESSION_ID_KEY,
      -1
      /* StorageScope.APPLICATION */
    );
    if (currentSessionId && manifest && currentSessionId !== manifest.session) {
      this.C();
    }
    if (manifest === null && currentSessionId) {
      this.C();
    }
    if (manifest) {
      this.s.store(
        USER_SESSION_ID_KEY,
        manifest.session,
        -1,
        1
        /* StorageTarget.MACHINE */
      );
    }
    return manifest;
  }
  async clear() {
    if (!this.a) {
      throw new Error("No settings sync store url configured.");
    }
    await this.deleteCollection();
    await this.deleteResources();
    this.C();
  }
  async getActivityData() {
    if (!this.a) {
      throw new Error("No settings sync store url configured.");
    }
    const url = $Ah(this.a, "download").toString();
    const headers = {};
    const context = await this.D(url, { type: "GET", headers }, [], CancellationToken.None);
    if (!$sq(context)) {
      throw new $Srb("Server returned " + context.res.statusCode, url, "EmptyResponse", context.res.statusCode, context.res.headers[$Orb]);
    }
    if ($tq(context)) {
      throw new $Srb("Empty response", url, "EmptyResponse", context.res.statusCode, context.res.headers[$Orb]);
    }
    return context.stream;
  }
  z(userDataSyncStoreUrl, collection, resource) {
    return collection ? $Ah(userDataSyncStoreUrl, "collection", collection, "resource", resource) : $Ah(userDataSyncStoreUrl, "resource", resource);
  }
  C() {
    this.s.remove(
      USER_SESSION_ID_KEY,
      -1
      /* StorageScope.APPLICATION */
    );
    this.s.remove(
      MACHINE_SESSION_ID_KEY,
      -1
      /* StorageScope.APPLICATION */
    );
  }
  async D(url, options, successCodes, token) {
    if (!this.b) {
      throw new $Srb("No Auth Token Available", url, "Unauthorized", void 0, void 0);
    }
    if (this.j && Date.now() < this.j.getTime()) {
      throw new $Srb(`${options.type} request '${url}' failed because of too many requests (429).`, url, "TooManyRequestsAndRetryAfter", void 0, void 0);
    }
    this.y(void 0);
    const commonHeaders = await this.c;
    options.headers = {
      ...options.headers || {},
      ...commonHeaders,
      "X-Account-Type": this.b.type,
      "authorization": `Bearer ${this.b.token}`
    };
    this.F(options.headers);
    this.r.trace("Sending request to server", { url, type: options.type, headers: { ...options.headers, ...{ authorization: void 0 } } });
    let context;
    try {
      context = await this.f.request(url, options, token);
    } catch (e) {
      if (!(e instanceof $Srb)) {
        let code = "RequestFailed";
        const errorMessage = $kb(e).toLowerCase();
        if (errorMessage.includes("xhr timeout")) {
          code = "RequestTimeout";
        } else if (errorMessage.includes("protocol") && errorMessage.includes("not supported")) {
          code = "RequestProtocolNotSupported";
        } else if (errorMessage.includes("request path contains unescaped characters")) {
          code = "RequestPathNotEscaped";
        } else if (errorMessage.includes("headers must be an object")) {
          code = "RequestHeadersNotObject";
        } else if ($eb(e)) {
          code = "RequestCanceled";
        }
        e = new $Srb(`Connection refused for the request '${url}'.`, url, code, void 0, void 0);
      }
      this.r.info("Request failed", url);
      throw e;
    }
    const operationId = context.res.headers[$Orb];
    const requestInfo = { url, status: context.res.statusCode, "execution-id": options.headers[$Prb], "operation-id": operationId };
    const isSuccess = $sq(context) || context.res.statusCode && successCodes.includes(context.res.statusCode);
    let failureMessage = "";
    if (isSuccess) {
      this.r.trace("Request succeeded", requestInfo);
    } else {
      failureMessage = await $uq(context) || "";
      this.r.info("Request failed", requestInfo, failureMessage);
    }
    if (context.res.statusCode === 401 || context.res.statusCode === 403) {
      this.b = void 0;
      if (context.res.statusCode === 401) {
        this.g.fire(
          "Unauthorized"
          /* UserDataSyncErrorCode.Unauthorized */
        );
        throw new $Srb(`${options.type} request '${url}' failed because of Unauthorized (401).`, url, "Unauthorized", context.res.statusCode, operationId);
      }
      if (context.res.statusCode === 403) {
        this.g.fire(
          "Forbidden"
          /* UserDataSyncErrorCode.Forbidden */
        );
        throw new $Srb(`${options.type} request '${url}' failed because the access is forbidden (403).`, url, "Forbidden", context.res.statusCode, operationId);
      }
    }
    this.h.fire();
    if (context.res.statusCode === 404) {
      throw new $Srb(`${options.type} request '${url}' failed because the requested resource is not found (404).`, url, "NotFound", context.res.statusCode, operationId);
    }
    if (context.res.statusCode === 405) {
      throw new $Srb(`${options.type} request '${url}' failed because the requested endpoint is not found (405). ${failureMessage}`, url, "MethodNotFound", context.res.statusCode, operationId);
    }
    if (context.res.statusCode === 409) {
      throw new $Srb(`${options.type} request '${url}' failed because of Conflict (409). There is new data for this resource. Make the request again with latest data.`, url, "Conflict", context.res.statusCode, operationId);
    }
    if (context.res.statusCode === 410) {
      throw new $Srb(`${options.type} request '${url}' failed because the requested resource is not longer available (410).`, url, "Gone", context.res.statusCode, operationId);
    }
    if (context.res.statusCode === 412) {
      throw new $Srb(`${options.type} request '${url}' failed because of Precondition Failed (412). There is new data for this resource. Make the request again with latest data.`, url, "PreconditionFailed", context.res.statusCode, operationId);
    }
    if (context.res.statusCode === 413) {
      throw new $Srb(`${options.type} request '${url}' failed because of too large payload (413).`, url, "TooLarge", context.res.statusCode, operationId);
    }
    if (context.res.statusCode === 426) {
      throw new $Srb(`${options.type} request '${url}' failed with status Upgrade Required (426). Please upgrade the client and try again.`, url, "UpgradeRequired", context.res.statusCode, operationId);
    }
    if (context.res.statusCode === 429) {
      const retryAfter = context.res.headers["retry-after"];
      if (retryAfter) {
        this.y(new Date(Date.now() + parseInt(retryAfter) * 1e3));
        throw new $Srb(`${options.type} request '${url}' failed because of too many requests (429).`, url, "TooManyRequestsAndRetryAfter", context.res.statusCode, operationId);
      } else {
        throw new $Srb(`${options.type} request '${url}' failed because of too many requests (429).`, url, "RemoteTooManyRequests", context.res.statusCode, operationId);
      }
    }
    if (!isSuccess) {
      throw new $Srb("Server returned " + context.res.statusCode, url, "Unknown", context.res.statusCode, operationId);
    }
    return context;
  }
  F(headers) {
    let machineSessionId = this.s.get(
      MACHINE_SESSION_ID_KEY,
      -1
      /* StorageScope.APPLICATION */
    );
    if (machineSessionId === void 0) {
      machineSessionId = $jh();
      this.s.store(
        MACHINE_SESSION_ID_KEY,
        machineSessionId,
        -1,
        1
        /* StorageTarget.MACHINE */
      );
    }
    headers["X-Machine-Session-Id"] = machineSessionId;
    const userSessionId = this.s.get(
      USER_SESSION_ID_KEY,
      -1
      /* StorageScope.APPLICATION */
    );
    if (userSessionId !== void 0) {
      headers["X-User-Session-Id"] = userSessionId;
    }
  }
};
$cTb = __decorate([
  __param(1, $Nk),
  __param(2, $qq),
  __param(3, $2rb),
  __param(4, $7i),
  __param(5, $ul),
  __param(6, $Dq)
], $cTb);
var $dTb = class $dTb2 extends $cTb {
  constructor(userDataSyncStoreManagementService, productService, requestService, logService, environmentService, fileService, storageService) {
    super(userDataSyncStoreManagementService.userDataSyncStore?.url, productService, requestService, logService, environmentService, fileService, storageService);
    this.B(userDataSyncStoreManagementService.onDidChangeUserDataSyncStore(() => this.t(userDataSyncStoreManagementService.userDataSyncStore?.url)));
  }
};
$dTb = __decorate([
  __param(0, $Lrb),
  __param(1, $Nk),
  __param(2, $qq),
  __param(3, $2rb),
  __param(4, $7i),
  __param(5, $ul),
  __param(6, $Dq)
], $dTb);
var $eTb = class {
  constructor(c, d, f, g) {
    this.c = c;
    this.d = d;
    this.f = f;
    this.g = g;
    this.a = [];
    this.b = void 0;
  }
  request(url, options, token) {
    if (this.h()) {
      this.i();
    }
    options.url = url;
    if (this.a.length >= this.c) {
      this.g.info("Too many requests", ...this.a);
      throw new $Srb(`Too many requests. Only ${this.c} requests allowed in ${this.d / (1e3 * 60)} minutes.`, url, "LocalTooManyRequests", void 0, void 0);
    }
    this.b = this.b || /* @__PURE__ */ new Date();
    this.a.push(url);
    return this.f.request(options, token);
  }
  h() {
    return this.b !== void 0 && (/* @__PURE__ */ new Date()).getTime() - this.b.getTime() > this.d;
  }
  i() {
    this.a = [];
    this.b = void 0;
  }
};

// out-build/vs/platform/userDataSync/common/userDataSyncIpc.js
var $emc = class {
  constructor(a) {
    this.a = a;
  }
  listen(_, event) {
    switch (event) {
      case "onDidChangeAccount":
        return this.a.onDidChangeAccount;
      case "onTokenFailed":
        return this.a.onTokenFailed;
    }
    throw new Error(`[UserDataSyncAccountServiceChannel] Event not found: ${event}`);
  }
  call(context, command, args) {
    switch (command) {
      case "_getInitialData":
        return Promise.resolve(this.a.account);
      case "updateAccount":
        return this.a.updateAccount(args);
    }
    throw new Error("Invalid call");
  }
};
var $gmc = class {
  constructor(a) {
    this.a = a;
  }
  listen(_, event) {
    switch (event) {
      case "onDidChangeUserDataSyncStore":
        return this.a.onDidChangeUserDataSyncStore;
    }
    throw new Error(`[UserDataSyncStoreManagementServiceChannel] Event not found: ${event}`);
  }
  call(context, command, args) {
    switch (command) {
      case "switch":
        return this.a.switch(args[0]);
      case "getPreviousUserDataSyncStore":
        return this.a.getPreviousUserDataSyncStore();
    }
    throw new Error("Invalid call");
  }
};
var $hmc = class $hmc2 extends $aTb {
  constructor(n, productService, configurationService, storageService) {
    super(productService, configurationService, storageService);
    this.n = n;
    this.B(this.n.listen("onDidChangeUserDataSyncStore")(() => this.j()));
  }
  async switch(type2) {
    return this.n.call("switch", [type2]);
  }
  async getPreviousUserDataSyncStore() {
    const userDataSyncStore = await this.n.call("getPreviousUserDataSyncStore");
    return this.r(userDataSyncStore);
  }
  r(userDataSyncStore) {
    return {
      url: URI.revive(userDataSyncStore.url),
      type: userDataSyncStore.type,
      defaultUrl: URI.revive(userDataSyncStore.defaultUrl),
      insidersUrl: URI.revive(userDataSyncStore.insidersUrl),
      stableUrl: URI.revive(userDataSyncStore.stableUrl),
      canSwitch: userDataSyncStore.canSwitch,
      authenticationProviders: userDataSyncStore.authenticationProviders
    };
  }
};
$hmc = __decorate([
  __param(1, $Nk),
  __param(2, $tj),
  __param(3, $Dq)
], $hmc);

// out-build/vs/platform/userDataSync/common/userDataSyncLog.js
var $cUb = class $cUb2 extends $zk {
  constructor(loggerService, environmentService) {
    super();
    this.g = this.B(loggerService.createLogger($Ah(environmentService.logsHome, `${$3rb}.log`), { id: $3rb, name: localize(2474, null) }));
  }
  trace(message, ...args) {
    this.g.trace(message, ...args);
  }
  debug(message, ...args) {
    this.g.debug(message, ...args);
  }
  info(message, ...args) {
    this.g.info(message, ...args);
  }
  warn(message, ...args) {
    this.g.warn(message, ...args);
  }
  error(message, ...args) {
    this.g.error(message, ...args);
  }
  flush() {
    this.g.flush();
  }
};
$cUb = __decorate([
  __param(0, $vk),
  __param(1, $7i)
], $cUb);

// out-build/vs/platform/userDataSync/common/userDataSyncMachines.js
var $Arb_1;
var $yrb = $Zi("IUserDataSyncMachinesService");
var currentMachineNameKey = "sync.currentMachineName";
var Safari = "Safari";
var Chrome = "Chrome";
var Edge = "Edge";
var Firefox = "Firefox";
var Android = "Android";
function getPlatformName() {
  if ($J) {
    return Safari;
  }
  if ($H) {
    return Chrome;
  }
  if ($K) {
    return Edge;
  }
  if ($I) {
    return Firefox;
  }
  if ($L) {
    return Android;
  }
  return $k($r ? 0 : $x);
}
var $Arb = class $Arb2 extends $0c {
  static {
    $Arb_1 = this;
  }
  static {
    this.a = 1;
  }
  static {
    this.b = "machines";
  }
  constructor(environmentService, fileService, h, j, m, n) {
    super();
    this.h = h;
    this.j = j;
    this.m = m;
    this.n = n;
    this.c = this.B(new $De());
    this.onDidChange = this.c.event;
    this.g = null;
    this.f = $Jq(environmentService, fileService, h);
  }
  async getMachines(manifest) {
    const currentMachineId = await this.f;
    const machineData = await this.s(manifest);
    return machineData.machines.map((machine) => ({ ...machine, ...{ isCurrent: machine.id === currentMachineId } }));
  }
  async addCurrentMachine(manifest) {
    const currentMachineId = await this.f;
    const machineData = await this.s(manifest);
    if (!machineData.machines.some(({ id: id2 }) => id2 === currentMachineId)) {
      machineData.machines.push({ id: currentMachineId, name: this.r(machineData.machines), platform: getPlatformName() });
      await this.t(machineData);
    }
  }
  async removeCurrentMachine(manifest) {
    const currentMachineId = await this.f;
    const machineData = await this.s(manifest);
    const updatedMachines = machineData.machines.filter(({ id: id2 }) => id2 !== currentMachineId);
    if (updatedMachines.length !== machineData.machines.length) {
      machineData.machines = updatedMachines;
      await this.t(machineData);
    }
  }
  async renameMachine(machineId, name, manifest) {
    const machineData = await this.s(manifest);
    const machine = machineData.machines.find(({ id: id2 }) => id2 === machineId);
    if (machine) {
      machine.name = name;
      await this.t(machineData);
      const currentMachineId = await this.f;
      if (machineId === currentMachineId) {
        this.h.store(
          currentMachineNameKey,
          name,
          -1,
          1
          /* StorageTarget.MACHINE */
        );
      }
    }
  }
  async setEnablements(enablements) {
    const machineData = await this.s();
    for (const [machineId, enabled] of enablements) {
      const machine = machineData.machines.find((machine2) => machine2.id === machineId);
      if (machine) {
        machine.disabled = enabled ? void 0 : true;
      }
    }
    await this.t(machineData);
  }
  r(machines) {
    const previousName = this.h.get(
      currentMachineNameKey,
      -1
      /* StorageScope.APPLICATION */
    );
    if (previousName) {
      return previousName;
    }
    const namePrefix = `${this.n.embedderIdentifier ? `${this.n.embedderIdentifier} - ` : ""}${getPlatformName()} (${this.n.nameShort})`;
    const nameRegEx = new RegExp(`${$Af(namePrefix)}\\s#(\\d+)`);
    let nameIndex = 0;
    for (const machine of machines) {
      const matches = nameRegEx.exec(machine.name);
      const index = matches ? parseInt(matches[1]) : 0;
      nameIndex = index > nameIndex ? index : nameIndex;
    }
    return `${namePrefix} #${nameIndex + 1}`;
  }
  async s(manifest) {
    this.g = await this.u(manifest);
    const machinesData = this.w(this.g);
    if (machinesData.version !== $Arb_1.a) {
      throw new Error(localize(2475, null, this.n.nameLong));
    }
    return machinesData;
  }
  async t(machinesData) {
    const content = JSON.stringify(machinesData);
    const ref = await this.j.writeResource($Arb_1.b, content, this.g?.ref || null);
    this.g = { ref, content };
    this.c.fire();
  }
  async u(manifest) {
    if (this.g) {
      const latestRef = manifest && manifest.latest ? manifest.latest[$Arb_1.b] : void 0;
      if (this.g.ref === latestRef) {
        return this.g;
      }
      if (latestRef === void 0 && this.g.content === null) {
        return this.g;
      }
    }
    return this.j.readResource($Arb_1.b, this.g);
  }
  w(userData) {
    if (userData.content !== null) {
      try {
        return JSON.parse(userData.content);
      } catch (e) {
        this.m.error(e);
      }
    }
    return {
      version: $Arb_1.a,
      machines: []
    };
  }
};
$Arb = $Arb_1 = __decorate([
  __param(0, $7i),
  __param(1, $ul),
  __param(2, $Dq),
  __param(3, $Mrb),
  __param(4, $2rb),
  __param(5, $Nk)
], $Arb);

// out-build/vs/platform/userDataSync/common/userDataSyncEnablementService.js
var enablementKey = "sync.enable";
var $Fic = class $Fic2 extends $0c {
  constructor(c, f, g, h) {
    super();
    this.c = c;
    this.f = f;
    this.g = g;
    this.h = h;
    this.a = new $De();
    this.onDidChangeEnablement = this.a.event;
    this.b = new $De();
    this.onDidChangeResourceEnablement = this.b.event;
    this.B(c.onDidChangeValue(-1, void 0, this.B(new $9c()))((e) => this.m(e)));
  }
  isEnabled() {
    switch (this.g.sync) {
      case "on":
        return true;
      case "off":
        return false;
    }
    return this.c.getBoolean(enablementKey, -1, false);
  }
  canToggleEnablement() {
    return this.h.userDataSyncStore !== void 0 && this.g.sync === void 0;
  }
  setEnablement(enabled) {
    if (enabled && !this.canToggleEnablement()) {
      return;
    }
    this.f.publicLog2(enablementKey, { enabled });
    this.c.store(
      enablementKey,
      enabled,
      -1,
      1
      /* StorageTarget.MACHINE */
    );
  }
  isResourceEnabled(resource) {
    return this.c.getBoolean($Vrb(resource), -1, true);
  }
  setResourceEnablement(resource, enabled) {
    if (this.isResourceEnabled(resource) !== enabled) {
      const resourceEnablementKey = $Vrb(resource);
      this.j(resourceEnablementKey, enabled);
    }
  }
  getResourceSyncStateVersion(resource) {
    return void 0;
  }
  j(resourceEnablementKey, enabled) {
    this.c.store(
      resourceEnablementKey,
      enabled,
      -1,
      $r ? 0 : 1
      /* StorageTarget.MACHINE */
    );
  }
  m(storageChangeEvent) {
    if (enablementKey === storageChangeEvent.key) {
      this.a.fire(this.isEnabled());
      return;
    }
    const resourceKey = $Irb.filter((resourceKey2) => $Vrb(resourceKey2) === storageChangeEvent.key)[0];
    if (resourceKey) {
      this.b.fire([resourceKey, this.isResourceEnabled(resourceKey)]);
      return;
    }
  }
};
$Fic = __decorate([
  __param(0, $Dq),
  __param(1, $tm),
  __param(2, $7i),
  __param(3, $Lrb)
], $Fic);

// out-build/vs/platform/userDataSync/common/abstractSynchronizer.js
function $fTb(thing) {
  if (thing && (thing.ref !== void 0 && typeof thing.ref === "string" && thing.ref !== "") && (thing.syncData !== void 0 && (thing.syncData === null || $gTb(thing.syncData)))) {
    return true;
  }
  return false;
}
function $gTb(thing) {
  if (thing && (thing.version !== void 0 && typeof thing.version === "number") && (thing.content !== void 0 && typeof thing.content === "string")) {
    if (Object.keys(thing).length === 2) {
      return true;
    }
    if (Object.keys(thing).length === 3 && (thing.machineId !== void 0 && typeof thing.machineId === "string")) {
      return true;
    }
  }
  return false;
}
function $hTb(syncResource, profile) {
  return `${$qg(syncResource)}${profile.isDefault ? "" : ` (${profile.name})`}`;
}
var $iTb = class $iTb2 extends $0c {
  get status() {
    return this.m;
  }
  get conflicts() {
    return { ...this.syncResource, conflicts: this.s };
  }
  constructor(syncResource, collection, G, H, I, J, L, M, N, O, P, uriIdentityService) {
    super();
    this.syncResource = syncResource;
    this.collection = collection;
    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.c = null;
    this.m = "idle";
    this.n = this.B(new $De());
    this.onDidChangeStatus = this.n.event;
    this.s = [];
    this.t = this.B(new $De());
    this.onDidChangeConflicts = this.t.event;
    this.u = this.B(new $Xh(50));
    this.w = this.B(new $De());
    this.onDidChangeLocal = this.w.event;
    this.z = `${this.collection ? `${this.collection}.` : ""}${this.syncResource.syncResource}.lastSyncUserData`;
    this.C = false;
    this.F = {};
    this.resource = this.syncResource.syncResource;
    this.D = $hTb(syncResource.syncResource, syncResource.profile);
    this.h = uriIdentityService.extUri;
    this.f = this.h.joinPath(H.userDataSyncHome, ...$Jrb(syncResource.profile.isDefault ? void 0 : syncResource.profile.id, syncResource.syncResource));
    this.g = this.h.joinPath(this.f, $5rb);
    this.y = $Krb(syncResource.profile.isDefault ? void 0 : syncResource.profile.id, syncResource.syncResource, H, this.h);
    this.j = $Jq(H, G, I);
  }
  Q() {
    this.u.trigger(() => this.R());
  }
  async R() {
    if (this.status === "hasConflicts") {
      this.O.info(`${this.D}: In conflicts state and local change detected. Syncing again...`);
      const preview = await this.c;
      this.c = null;
      const status = await this.Y(preview.remoteUserData, preview.lastSyncUserData, true, this.ob());
      this.S(status);
    } else {
      this.O.trace(`${this.D}: Checking for local changes...`);
      const lastSyncUserData = await this.getLastSyncUserData();
      const hasRemoteChanged = lastSyncUserData ? await this.ub(lastSyncUserData) : true;
      if (hasRemoteChanged) {
        this.w.fire();
      }
    }
  }
  S(status) {
    if (this.m !== status) {
      this.m = status;
      this.n.fire(status);
    }
  }
  async sync(manifest, headers = {}) {
    await this.U(manifest, true, this.ob(), headers);
  }
  async preview(manifest, userDataSyncConfiguration, headers = {}) {
    return this.U(manifest, false, userDataSyncConfiguration, headers);
  }
  async apply(force, headers = {}) {
    try {
      this.F = { ...headers };
      const status = await this.ab(force);
      this.S(status);
      return this.c;
    } finally {
      this.F = {};
    }
  }
  async U(manifest, apply, userDataSyncConfiguration, headers) {
    try {
      this.F = { ...headers };
      if (this.status === "hasConflicts") {
        this.O.info(`${this.D}: Skipped synchronizing ${this.resource.toLowerCase()} as there are conflicts.`);
        return this.c;
      }
      if (this.status === "syncing") {
        this.O.info(`${this.D}: Skipped synchronizing ${this.resource.toLowerCase()} as it is running already.`);
        return this.c;
      }
      this.O.trace(`${this.D}: Started synchronizing ${this.resource.toLowerCase()}...`);
      this.S(
        "syncing"
        /* SyncStatus.Syncing */
      );
      let status = "idle";
      try {
        const lastSyncUserData = await this.getLastSyncUserData();
        const remoteUserData = await this.X(manifest, lastSyncUserData);
        status = await this.Y(remoteUserData, lastSyncUserData, apply, userDataSyncConfiguration);
        if (status === "hasConflicts") {
          this.O.info(`${this.D}: Detected conflicts while synchronizing ${this.resource.toLowerCase()}.`);
        } else if (status === "idle") {
          this.O.trace(`${this.D}: Finished synchronizing ${this.resource.toLowerCase()}.`);
        }
        return this.c || null;
      } finally {
        this.S(status);
      }
    } finally {
      this.F = {};
    }
  }
  async replace(content) {
    const syncData = this.kb(content);
    if (!syncData) {
      return false;
    }
    await this.stop();
    try {
      this.O.trace(`${this.D}: Started resetting ${this.resource.toLowerCase()}...`);
      this.S(
        "syncing"
        /* SyncStatus.Syncing */
      );
      const lastSyncUserData = await this.getLastSyncUserData();
      const remoteUserData = await this.X(null, lastSyncUserData);
      const isRemoteDataFromCurrentMachine = await this.W(remoteUserData);
      const resourcePreviewResults = await this.qb({ ref: remoteUserData.ref, syncData }, lastSyncUserData, isRemoteDataFromCurrentMachine, this.ob(), CancellationToken.None);
      const resourcePreviews = [];
      for (const resourcePreviewResult of resourcePreviewResults) {
        const acceptResult = await this.sb(resourcePreviewResult, resourcePreviewResult.remoteResource, void 0, CancellationToken.None);
        const { remoteChange } = await this.sb(resourcePreviewResult, resourcePreviewResult.previewResource, resourcePreviewResult.remoteContent, CancellationToken.None);
        resourcePreviews.push([resourcePreviewResult, {
          ...acceptResult,
          remoteChange: remoteChange !== 0 ? remoteChange : 2
          /* Change.Modified */
        }]);
      }
      await this.tb(remoteUserData, lastSyncUserData, resourcePreviews, false);
      this.O.info(`${this.D}: Finished resetting ${this.resource.toLowerCase()}.`);
    } finally {
      this.S(
        "idle"
        /* SyncStatus.Idle */
      );
    }
    return true;
  }
  async W(remoteUserData) {
    const machineId = await this.j;
    return !!remoteUserData.syncData?.machineId && remoteUserData.syncData.machineId === machineId;
  }
  async X(manifest, lastSyncUserData) {
    if (lastSyncUserData) {
      const latestRef = manifest ? manifest[this.resource] : void 0;
      if (lastSyncUserData.ref === latestRef) {
        return lastSyncUserData;
      }
      if (latestRef === void 0 && lastSyncUserData.syncData === null) {
        return lastSyncUserData;
      }
    }
    return this.getRemoteUserData(lastSyncUserData);
  }
  async Y(remoteUserData, lastSyncUserData, apply, userDataSyncConfiguration) {
    if (remoteUserData.syncData && remoteUserData.syncData.version > this.pb) {
      this.N.publicLog2("sync/incompatible", { source: this.resource });
      throw new $Rrb(localize(2457, null, this.resource, this.pb, remoteUserData.syncData.version), "IncompatibleLocalContent", this.resource);
    }
    try {
      return await this.Z(remoteUserData, lastSyncUserData, apply, userDataSyncConfiguration);
    } catch (e) {
      if (e instanceof $Rrb) {
        switch (e.code) {
          case "LocalPreconditionFailed":
            this.O.info(`${this.D}: Failed to synchronize ${this.D} as there is a new local version available. Synchronizing again...`);
            return this.Y(remoteUserData, lastSyncUserData, apply, userDataSyncConfiguration);
          case "Conflict":
          case "PreconditionFailed":
            this.O.info(`${this.D}: Failed to synchronize as there is a new remote version available. Synchronizing again...`);
            remoteUserData = await this.getRemoteUserData(null);
            lastSyncUserData = await this.getLastSyncUserData();
            return this.Y(remoteUserData, lastSyncUserData, apply, userDataSyncConfiguration);
        }
      }
      throw e;
    }
  }
  async Z(remoteUserData, lastSyncUserData, apply, userDataSyncConfiguration) {
    try {
      const isRemoteDataFromCurrentMachine = await this.W(remoteUserData);
      const acceptRemote = !isRemoteDataFromCurrentMachine && lastSyncUserData === null && this.gb() !== void 0;
      const merge2 = apply && !acceptRemote;
      if (!this.c) {
        this.c = $Mh((token) => this.eb(remoteUserData, lastSyncUserData, isRemoteDataFromCurrentMachine, merge2, userDataSyncConfiguration, token));
      }
      let preview = await this.c;
      if (apply && acceptRemote) {
        this.O.info(`${this.D}: Accepting remote because it was synced before and the last sync data is not available.`);
        for (const resourcePreview of preview.resourcePreviews) {
          preview = await this.accept(resourcePreview.remoteResource) || preview;
        }
      }
      this.cb(preview.resourcePreviews);
      if (preview.resourcePreviews.some(
        ({ mergeState }) => mergeState === "conflict"
        /* MergeState.Conflict */
      )) {
        return "hasConflicts";
      }
      if (apply) {
        return await this.ab(false);
      }
      return "syncing";
    } catch (error) {
      this.c = null;
      throw error;
    }
  }
  async merge(resource) {
    await this.$(resource, async (resourcePreview) => {
      const mergeResult = await this.rb(resourcePreview, CancellationToken.None);
      await this.G.writeFile(resourcePreview.previewResource, $7e.fromString(mergeResult?.content || ""));
      const acceptResult = mergeResult && !mergeResult.hasConflicts ? await this.sb(resourcePreview, resourcePreview.previewResource, void 0, CancellationToken.None) : void 0;
      resourcePreview.acceptResult = acceptResult;
      resourcePreview.mergeState = mergeResult.hasConflicts ? "conflict" : acceptResult ? "accepted" : "preview";
      resourcePreview.localChange = acceptResult ? acceptResult.localChange : mergeResult.localChange;
      resourcePreview.remoteChange = acceptResult ? acceptResult.remoteChange : mergeResult.remoteChange;
      return resourcePreview;
    });
    return this.c;
  }
  async accept(resource, content) {
    await this.$(resource, async (resourcePreview) => {
      const acceptResult = await this.sb(resourcePreview, resource, content, CancellationToken.None);
      resourcePreview.acceptResult = acceptResult;
      resourcePreview.mergeState = "accepted";
      resourcePreview.localChange = acceptResult.localChange;
      resourcePreview.remoteChange = acceptResult.remoteChange;
      return resourcePreview;
    });
    return this.c;
  }
  async discard(resource) {
    await this.$(resource, async (resourcePreview) => {
      const mergeResult = await this.rb(resourcePreview, CancellationToken.None);
      await this.G.writeFile(resourcePreview.previewResource, $7e.fromString(mergeResult.content || ""));
      resourcePreview.acceptResult = void 0;
      resourcePreview.mergeState = "preview";
      resourcePreview.localChange = mergeResult.localChange;
      resourcePreview.remoteChange = mergeResult.remoteChange;
      return resourcePreview;
    });
    return this.c;
  }
  async $(resource, updateResourcePreview) {
    if (!this.c) {
      return;
    }
    let preview = await this.c;
    const index = preview.resourcePreviews.findIndex(({ localResource, remoteResource, previewResource }) => this.h.isEqual(localResource, resource) || this.h.isEqual(remoteResource, resource) || this.h.isEqual(previewResource, resource));
    if (index === -1) {
      return;
    }
    this.c = $Mh(async (token) => {
      const resourcePreviews = [...preview.resourcePreviews];
      resourcePreviews[index] = await updateResourcePreview(resourcePreviews[index]);
      return {
        ...preview,
        resourcePreviews
      };
    });
    preview = await this.c;
    this.cb(preview.resourcePreviews);
    if (preview.resourcePreviews.some(
      ({ mergeState }) => mergeState === "conflict"
      /* MergeState.Conflict */
    )) {
      this.S(
        "hasConflicts"
        /* SyncStatus.HasConflicts */
      );
    } else {
      this.S(
        "syncing"
        /* SyncStatus.Syncing */
      );
    }
  }
  async ab(force) {
    if (!this.c) {
      return "idle";
    }
    const preview = await this.c;
    if (preview.resourcePreviews.some(
      ({ mergeState }) => mergeState === "conflict"
      /* MergeState.Conflict */
    )) {
      return "hasConflicts";
    }
    if (preview.resourcePreviews.some(
      ({ mergeState }) => mergeState !== "accepted"
      /* MergeState.Accepted */
    )) {
      return "syncing";
    }
    await this.tb(preview.remoteUserData, preview.lastSyncUserData, preview.resourcePreviews.map((resourcePreview) => [resourcePreview, resourcePreview.acceptResult]), force);
    this.c = null;
    await this.bb();
    return "idle";
  }
  async bb() {
    try {
      await this.G.del(this.g, { recursive: true });
    } catch (error) {
    }
  }
  cb(resourcePreviews) {
    const conflicts = resourcePreviews.filter(
      ({ mergeState }) => mergeState === "conflict"
      /* MergeState.Conflict */
    );
    if (!$Hb(this.s, conflicts, (a, b) => this.h.isEqual(a.previewResource, b.previewResource))) {
      this.s = conflicts;
      this.t.fire(this.conflicts);
    }
  }
  async hasPreviouslySynced() {
    const lastSyncData = await this.getLastSyncUserData();
    return !!lastSyncData && lastSyncData.syncData !== null;
  }
  async db(uri) {
    const syncPreview = this.c ? await this.c : null;
    if (syncPreview) {
      for (const resourcePreview of syncPreview.resourcePreviews) {
        if (this.h.isEqual(resourcePreview.acceptedResource, uri)) {
          return resourcePreview.acceptResult ? resourcePreview.acceptResult.content : null;
        }
        if (this.h.isEqual(resourcePreview.remoteResource, uri)) {
          return resourcePreview.remoteContent;
        }
        if (this.h.isEqual(resourcePreview.localResource, uri)) {
          return resourcePreview.localContent;
        }
        if (this.h.isEqual(resourcePreview.baseResource, uri)) {
          return resourcePreview.baseContent;
        }
      }
    }
    return null;
  }
  async resetLocal() {
    this.I.remove(
      this.z,
      -1
      /* StorageScope.APPLICATION */
    );
    try {
      await this.G.del(this.y);
    } catch (error) {
      if ($Ll(error) !== 1) {
        this.O.error(error);
      }
    }
  }
  async eb(remoteUserData, lastSyncUserData, isRemoteDataFromCurrentMachine, merge2, userDataSyncConfiguration, token) {
    const resourcePreviewResults = await this.qb(remoteUserData, lastSyncUserData, isRemoteDataFromCurrentMachine, userDataSyncConfiguration, token);
    const resourcePreviews = [];
    for (const resourcePreviewResult of resourcePreviewResults) {
      const acceptedResource = resourcePreviewResult.previewResource.with({ scheme: $4rb, authority: "accepted" });
      if (resourcePreviewResult.localChange === 0 && resourcePreviewResult.remoteChange === 0) {
        resourcePreviews.push({
          ...resourcePreviewResult,
          acceptedResource,
          acceptResult: {
            content: null,
            localChange: 0,
            remoteChange: 0
            /* Change.None */
          },
          mergeState: "accepted"
          /* MergeState.Accepted */
        });
      } else {
        const mergeResult = merge2 ? await this.rb(resourcePreviewResult, token) : void 0;
        if (token.isCancellationRequested) {
          break;
        }
        await this.G.writeFile(resourcePreviewResult.previewResource, $7e.fromString(mergeResult?.content || ""));
        const acceptResult = mergeResult && !mergeResult.hasConflicts ? await this.sb(resourcePreviewResult, resourcePreviewResult.previewResource, void 0, token) : void 0;
        resourcePreviews.push({
          ...resourcePreviewResult,
          acceptResult,
          mergeState: mergeResult?.hasConflicts ? "conflict" : acceptResult ? "accepted" : "preview",
          localChange: acceptResult ? acceptResult.localChange : mergeResult ? mergeResult.localChange : resourcePreviewResult.localChange,
          remoteChange: acceptResult ? acceptResult.remoteChange : mergeResult ? mergeResult.remoteChange : resourcePreviewResult.remoteChange
        });
      }
    }
    return { syncResource: this.resource, profile: this.syncResource.profile, remoteUserData, lastSyncUserData, resourcePreviews, isLastSyncFromCurrentMachine: isRemoteDataFromCurrentMachine };
  }
  async getLastSyncUserData() {
    let storedLastSyncUserDataStateContent = this.gb();
    if (!storedLastSyncUserDataStateContent) {
      storedLastSyncUserDataStateContent = await this.jb();
    }
    if (!storedLastSyncUserDataStateContent) {
      this.O.info(`${this.D}: Last sync data state does not exist.`);
      return null;
    }
    const lastSyncUserDataState = JSON.parse(storedLastSyncUserDataStateContent);
    const resourceSyncStateVersion = this.M.getResourceSyncStateVersion(this.resource);
    this.C = !!lastSyncUserDataState.version && !!resourceSyncStateVersion && lastSyncUserDataState.version !== resourceSyncStateVersion;
    if (this.C) {
      this.O.info(`${this.D}: Reset last sync state because last sync state version ${lastSyncUserDataState.version} is not compatible with current sync state version ${resourceSyncStateVersion}.`);
      await this.resetLocal();
      return null;
    }
    let syncData = void 0;
    let retrial = 1;
    while (syncData === void 0 && retrial++ < 6) {
      try {
        const lastSyncStoredRemoteUserData = await this.hb();
        if (lastSyncStoredRemoteUserData) {
          if (lastSyncStoredRemoteUserData.ref === lastSyncUserDataState.ref) {
            syncData = lastSyncStoredRemoteUserData.syncData;
          } else {
            this.O.info(`${this.D}: Last sync data stored locally is not same as the last sync state.`);
          }
        }
        break;
      } catch (error) {
        if (error instanceof $Pl && error.fileOperationResult === 1) {
          this.O.info(`${this.D}: Last sync resource does not exist locally.`);
          break;
        } else if (error instanceof $Rrb) {
          throw error;
        } else {
          this.O.error(error, retrial);
        }
      }
    }
    if (syncData === void 0) {
      try {
        const content = await this.J.resolveResourceContent(this.resource, lastSyncUserDataState.ref, this.collection, this.F);
        syncData = content === null ? null : this.kb(content);
        await this.ib({ ref: lastSyncUserDataState.ref, syncData });
      } catch (error) {
        if (error instanceof $Rrb && error.code === "NotFound") {
          this.O.info(`${this.D}: Last sync resource does not exist remotely.`);
        } else {
          throw error;
        }
      }
    }
    if (syncData === void 0) {
      return null;
    }
    return {
      ...lastSyncUserDataState,
      syncData
    };
  }
  async fb(lastSyncRemoteUserData, additionalProps = {}) {
    if (additionalProps["ref"] || additionalProps["version"]) {
      throw new Error("Cannot have core properties as additional");
    }
    const version = this.M.getResourceSyncStateVersion(this.resource);
    const lastSyncUserDataState = {
      ref: lastSyncRemoteUserData.ref,
      version,
      ...additionalProps
    };
    this.I.store(
      this.z,
      JSON.stringify(lastSyncUserDataState),
      -1,
      1
      /* StorageTarget.MACHINE */
    );
    await this.ib(lastSyncRemoteUserData);
  }
  gb() {
    return this.I.get(
      this.z,
      -1
      /* StorageScope.APPLICATION */
    );
  }
  async hb() {
    const content = (await this.G.readFile(this.y)).value.toString();
    try {
      const lastSyncStoredRemoteUserData = content ? JSON.parse(content) : void 0;
      if ($fTb(lastSyncStoredRemoteUserData)) {
        return lastSyncStoredRemoteUserData;
      }
    } catch (e) {
      this.O.error(e);
    }
    return void 0;
  }
  async ib(lastSyncRemoteUserData) {
    await this.G.writeFile(this.y, $7e.fromString(JSON.stringify(lastSyncRemoteUserData)));
  }
  async jb() {
    try {
      const content = await this.G.readFile(this.y);
      const userData = JSON.parse(content.value.toString());
      await this.G.del(this.y);
      if (userData.ref && userData.content !== void 0) {
        this.I.store(
          this.z,
          JSON.stringify({
            ...userData,
            content: void 0
          }),
          -1,
          1
          /* StorageTarget.MACHINE */
        );
        await this.ib({ ref: userData.ref, syncData: userData.content === null ? null : JSON.parse(userData.content) });
      } else {
        this.O.info(`${this.D}: Migrating last sync user data. Invalid data.`, userData);
      }
    } catch (error) {
      if (error instanceof $Pl && error.fileOperationResult === 1) {
        this.O.info(`${this.D}: Migrating last sync user data. Resource does not exist.`);
      } else {
        this.O.error(error);
      }
    }
    return this.I.get(
      this.z,
      -1
      /* StorageScope.APPLICATION */
    );
  }
  async getRemoteUserData(lastSyncData) {
    const { ref, content } = await this.lb(lastSyncData);
    let syncData = null;
    if (content !== null) {
      syncData = this.kb(content);
    }
    return { ref, syncData };
  }
  kb(content) {
    try {
      const syncData = JSON.parse(content);
      if ($gTb(syncData)) {
        return syncData;
      }
    } catch (error) {
      this.O.error(error);
    }
    throw new $Rrb(localize(2458, null), "IncompatibleRemoteContent", this.resource);
  }
  async lb(lastSyncData) {
    const lastSyncUserData = lastSyncData ? { ref: lastSyncData.ref, content: lastSyncData.syncData ? JSON.stringify(lastSyncData.syncData) : null } : null;
    return this.J.readResource(this.resource, lastSyncUserData, this.collection, this.F);
  }
  async mb(content, ref) {
    const machineId = await this.j;
    const syncData = { version: this.pb, machineId, content };
    try {
      ref = await this.J.writeResource(this.resource, JSON.stringify(syncData), ref, this.collection, this.F);
      return { ref, syncData };
    } catch (error) {
      if (error instanceof $Rrb && error.code === "TooLarge") {
        error = new $Rrb(error.message, error.code, this.resource);
      }
      throw error;
    }
  }
  async nb(content) {
    const syncData = { version: this.pb, content };
    return this.L.writeResource(this.resource, JSON.stringify(syncData), /* @__PURE__ */ new Date(), this.syncResource.profile.isDefault ? void 0 : this.syncResource.profile.id);
  }
  async stop() {
    if (this.status === "idle") {
      return;
    }
    this.O.trace(`${this.D}: Stopping synchronizing ${this.resource.toLowerCase()}.`);
    if (this.c) {
      this.c.cancel();
      this.c = null;
    }
    this.cb([]);
    await this.bb();
    this.S(
      "idle"
      /* SyncStatus.Idle */
    );
    this.O.info(`${this.D}: Stopped synchronizing ${this.resource.toLowerCase()}.`);
  }
  ob() {
    return this.P.getValue($Erb);
  }
};
$iTb = __decorate([
  __param(2, $ul),
  __param(3, $7i),
  __param(4, $Dq),
  __param(5, $Mrb),
  __param(6, $Nrb),
  __param(7, $Wrb),
  __param(8, $tm),
  __param(9, $2rb),
  __param(10, $tj),
  __param(11, $5l)
], $iTb);
var $jTb = class $jTb2 extends $iTb {
  constructor(r, syncResource, collection, fileService, environmentService, storageService, userDataSyncStoreService, userDataSyncLocalStoreService, userDataSyncEnablementService, telemetryService, logService, configurationService, uriIdentityService) {
    super(syncResource, collection, fileService, environmentService, storageService, userDataSyncStoreService, userDataSyncLocalStoreService, userDataSyncEnablementService, telemetryService, logService, configurationService, uriIdentityService);
    this.r = r;
    this.B(this.G.watch(this.h.dirname(r)));
    this.B(this.G.onDidFilesChange((e) => this.yb(e)));
  }
  async vb() {
    try {
      return await this.G.readFile(this.r);
    } catch (error) {
      return null;
    }
  }
  async wb(newContent, oldContent, force) {
    try {
      if (oldContent) {
        await this.G.writeFile(this.r, $7e.fromString(newContent), force ? void 0 : oldContent);
      } else {
        await this.G.createFile(this.r, $7e.fromString(newContent), { overwrite: force });
      }
    } catch (e) {
      if (e instanceof $Pl && e.fileOperationResult === 1 || e instanceof $Pl && e.fileOperationResult === 3) {
        throw new $Rrb(
          e.message,
          "LocalPreconditionFailed"
          /* UserDataSyncErrorCode.LocalPreconditionFailed */
        );
      } else {
        throw e;
      }
    }
  }
  async xb() {
    try {
      await this.G.del(this.r);
    } catch (e) {
      if (!(e instanceof $Pl && e.fileOperationResult === 1)) {
        throw e;
      }
    }
  }
  yb(e) {
    if (!e.contains(this.r)) {
      return;
    }
    this.Q();
  }
};
$jTb = __decorate([
  __param(3, $ul),
  __param(4, $7i),
  __param(5, $Dq),
  __param(6, $Mrb),
  __param(7, $Nrb),
  __param(8, $Wrb),
  __param(9, $tm),
  __param(10, $2rb),
  __param(11, $tj),
  __param(12, $5l)
], $jTb);
var $kTb = class $kTb2 extends $jTb {
  constructor(file, syncResource, collection, fileService, environmentService, storageService, userDataSyncStoreService, userDataSyncLocalStoreService, userDataSyncEnablementService, telemetryService, logService, zb, configurationService, uriIdentityService) {
    super(file, syncResource, collection, fileService, environmentService, storageService, userDataSyncStoreService, userDataSyncLocalStoreService, userDataSyncEnablementService, telemetryService, logService, configurationService, uriIdentityService);
    this.zb = zb;
    this.Bb = void 0;
  }
  Ab(content, isArray) {
    const parseErrors = [];
    const result = $ho(content, parseErrors, { allowEmptyContent: true, allowTrailingComma: true });
    return parseErrors.length > 0 || !$Fg(result) && isArray !== Array.isArray(result);
  }
  Cb() {
    if (!this.Bb) {
      this.Bb = this.zb.resolveFormattingOptions(this.r);
    }
    return this.Bb;
  }
};
$kTb = __decorate([
  __param(3, $ul),
  __param(4, $7i),
  __param(5, $Dq),
  __param(6, $Mrb),
  __param(7, $Nrb),
  __param(8, $Wrb),
  __param(9, $tm),
  __param(10, $2rb),
  __param(11, $1rb),
  __param(12, $tj),
  __param(13, $5l)
], $kTb);
var $lTb = class $lTb2 {
  constructor(resource, g, h, j, k, l, uriIdentityService) {
    this.resource = resource;
    this.g = g;
    this.h = h;
    this.j = j;
    this.k = k;
    this.l = l;
    this.d = uriIdentityService.extUri;
    this.f = $Krb(void 0, this.resource, h, this.d);
  }
  async initialize({ ref, content }) {
    if (!content) {
      this.j.info("Remote content does not exist.", this.resource);
      return;
    }
    const syncData = this.m(content);
    if (!syncData) {
      return;
    }
    try {
      await this.o({ ref, syncData });
    } catch (error) {
      this.j.error(error);
    }
  }
  m(content) {
    try {
      const syncData = JSON.parse(content);
      if ($gTb(syncData)) {
        return syncData;
      }
    } catch (error) {
      this.j.error(error);
    }
    this.j.info("Cannot parse sync data as it is not compatible with the current version.", this.resource);
    return void 0;
  }
  async n(lastSyncRemoteUserData, additionalProps = {}) {
    if (additionalProps["ref"] || additionalProps["version"]) {
      throw new Error("Cannot have core properties as additional");
    }
    const lastSyncUserDataState = {
      ref: lastSyncRemoteUserData.ref,
      version: void 0,
      ...additionalProps
    };
    this.l.store(
      `${this.resource}.lastSyncUserData`,
      JSON.stringify(lastSyncUserDataState),
      -1,
      1
      /* StorageTarget.MACHINE */
    );
    await this.k.writeFile(this.f, $7e.fromString(JSON.stringify(lastSyncRemoteUserData)));
  }
};
$lTb = __decorate([
  __param(1, $7l),
  __param(2, $7i),
  __param(3, $uk),
  __param(4, $ul),
  __param(5, $Dq),
  __param(6, $5l)
], $lTb);

// out-build/vs/platform/userDataSync/common/extensionsMerge.js
function $Qgc(localExtensions, remoteExtensions, lastSyncExtensions, skippedExtensions, ignoredExtensions, lastSyncBuiltinExtensions) {
  const added = [];
  const removed = [];
  const updated = [];
  if (!remoteExtensions) {
    const remote2 = localExtensions.filter(({ identifier }) => ignoredExtensions.every((id2) => id2.toLowerCase() !== identifier.id.toLowerCase()));
    return {
      local: {
        added,
        removed,
        updated
      },
      remote: remote2.length > 0 ? {
        added: remote2,
        updated: [],
        removed: [],
        all: remote2
      } : null
    };
  }
  localExtensions = localExtensions.map(massageIncomingExtension);
  remoteExtensions = remoteExtensions.map(massageIncomingExtension);
  lastSyncExtensions = lastSyncExtensions ? lastSyncExtensions.map(massageIncomingExtension) : null;
  const uuids = /* @__PURE__ */ new Map();
  const addUUID = (identifier) => {
    if (identifier.uuid) {
      uuids.set(identifier.id.toLowerCase(), identifier.uuid);
    }
  };
  localExtensions.forEach(({ identifier }) => addUUID(identifier));
  remoteExtensions.forEach(({ identifier }) => addUUID(identifier));
  lastSyncExtensions?.forEach(({ identifier }) => addUUID(identifier));
  skippedExtensions?.forEach(({ identifier }) => addUUID(identifier));
  lastSyncBuiltinExtensions?.forEach((identifier) => addUUID(identifier));
  const getKey = (extension) => {
    const uuid = extension.identifier.uuid || uuids.get(extension.identifier.id.toLowerCase());
    return uuid ? `uuid:${uuid}` : `id:${extension.identifier.id.toLowerCase()}`;
  };
  const addExtensionToMap = (map, extension) => {
    map.set(getKey(extension), extension);
    return map;
  };
  const localExtensionsMap = localExtensions.reduce(addExtensionToMap, /* @__PURE__ */ new Map());
  const remoteExtensionsMap = remoteExtensions.reduce(addExtensionToMap, /* @__PURE__ */ new Map());
  const newRemoteExtensionsMap = remoteExtensions.reduce((map, extension) => addExtensionToMap(map, $zo(extension)), /* @__PURE__ */ new Map());
  const lastSyncExtensionsMap = lastSyncExtensions ? lastSyncExtensions.reduce(addExtensionToMap, /* @__PURE__ */ new Map()) : null;
  const skippedExtensionsMap = skippedExtensions.reduce(addExtensionToMap, /* @__PURE__ */ new Map());
  const ignoredExtensionsSet = ignoredExtensions.reduce((set, id2) => {
    const uuid = uuids.get(id2.toLowerCase());
    return set.add(uuid ? `uuid:${uuid}` : `id:${id2.toLowerCase()}`);
  }, /* @__PURE__ */ new Set());
  const lastSyncBuiltinExtensionsSet = lastSyncBuiltinExtensions ? lastSyncBuiltinExtensions.reduce((set, { id: id2, uuid }) => {
    uuid = uuid ?? uuids.get(id2.toLowerCase());
    return set.add(uuid ? `uuid:${uuid}` : `id:${id2.toLowerCase()}`);
  }, /* @__PURE__ */ new Set()) : null;
  const localToRemote = compare3(localExtensionsMap, remoteExtensionsMap, ignoredExtensionsSet, false);
  if (localToRemote.added.size > 0 || localToRemote.removed.size > 0 || localToRemote.updated.size > 0) {
    const baseToLocal = compare3(lastSyncExtensionsMap, localExtensionsMap, ignoredExtensionsSet, false);
    const baseToRemote = compare3(lastSyncExtensionsMap, remoteExtensionsMap, ignoredExtensionsSet, true);
    const merge2 = (key, localExtension, remoteExtension, preferred) => {
      let pinned, version, preRelease;
      if (localExtension.installed) {
        pinned = preferred.pinned;
        preRelease = preferred.preRelease;
        if (pinned) {
          version = preferred.version;
        }
      } else {
        pinned = remoteExtension.pinned;
        preRelease = remoteExtension.preRelease;
        if (pinned) {
          version = remoteExtension.version;
        }
      }
      if (pinned === void 0) {
        pinned = localExtension.pinned;
        if (pinned) {
          version = localExtension.version;
        }
      }
      if (preRelease === void 0) {
        preRelease = localExtension.preRelease;
      }
      return {
        ...preferred,
        installed: localExtension.installed || remoteExtension.installed,
        pinned,
        preRelease,
        version: version ?? (remoteExtension.version && (!localExtension.installed || gt(remoteExtension.version, localExtension.version)) ? remoteExtension.version : localExtension.version),
        state: mergeExtensionState(localExtension, remoteExtension, lastSyncExtensionsMap?.get(key))
      };
    };
    for (const key of baseToRemote.removed.values()) {
      const localExtension = localExtensionsMap.get(key);
      if (!localExtension) {
        continue;
      }
      const baseExtension = $Jg(lastSyncExtensionsMap?.get(key));
      const wasAnInstalledExtensionDuringLastSync = lastSyncBuiltinExtensionsSet && !lastSyncBuiltinExtensionsSet.has(key) && baseExtension.installed;
      if (localExtension.installed && wasAnInstalledExtensionDuringLastSync) {
        removed.push(localExtension.identifier);
      } else {
        newRemoteExtensionsMap.set(key, localExtension);
      }
    }
    for (const key of baseToRemote.added.values()) {
      const remoteExtension = $Jg(remoteExtensionsMap.get(key));
      const localExtension = localExtensionsMap.get(key);
      if (localExtension) {
        if (localToRemote.updated.has(key)) {
          const mergedExtension = merge2(key, localExtension, remoteExtension, remoteExtension);
          if (!areSame(localExtension, remoteExtension, false, false)) {
            updated.push(massageOutgoingExtension(mergedExtension, key));
          }
          newRemoteExtensionsMap.set(key, mergedExtension);
        }
      } else {
        if (remoteExtension.installed) {
          added.push(massageOutgoingExtension(remoteExtension, key));
        }
      }
    }
    for (const key of baseToRemote.updated.values()) {
      const remoteExtension = $Jg(remoteExtensionsMap.get(key));
      const baseExtension = $Jg(lastSyncExtensionsMap?.get(key));
      const localExtension = localExtensionsMap.get(key);
      if (localExtension) {
        const wasAnInstalledExtensionDuringLastSync = lastSyncBuiltinExtensionsSet && !lastSyncBuiltinExtensionsSet.has(key) && baseExtension.installed;
        if (wasAnInstalledExtensionDuringLastSync && localExtension.installed && !remoteExtension.installed) {
          removed.push(localExtension.identifier);
        } else {
          const mergedExtension = merge2(key, localExtension, remoteExtension, remoteExtension);
          updated.push(massageOutgoingExtension(mergedExtension, key));
          newRemoteExtensionsMap.set(key, mergedExtension);
        }
      } else if (remoteExtension.installed) {
        added.push(massageOutgoingExtension(remoteExtension, key));
      }
    }
    for (const key of baseToLocal.added.values()) {
      if (baseToRemote.added.has(key)) {
        continue;
      }
      newRemoteExtensionsMap.set(key, $Jg(localExtensionsMap.get(key)));
    }
    for (const key of baseToLocal.updated.values()) {
      if (baseToRemote.removed.has(key)) {
        continue;
      }
      if (baseToRemote.updated.has(key)) {
        continue;
      }
      const localExtension = $Jg(localExtensionsMap.get(key));
      const remoteExtension = $Jg(remoteExtensionsMap.get(key));
      newRemoteExtensionsMap.set(key, merge2(key, localExtension, remoteExtension, localExtension));
    }
    for (const key of baseToLocal.removed.values()) {
      if (baseToRemote.updated.has(key)) {
        continue;
      }
      if (baseToRemote.removed.has(key)) {
        continue;
      }
      if (skippedExtensionsMap.has(key)) {
        continue;
      }
      if (!$Jg(remoteExtensionsMap.get(key)).installed) {
        continue;
      }
      if (!lastSyncBuiltinExtensionsSet) {
        continue;
      }
      if (lastSyncBuiltinExtensionsSet.has(key) || !$Jg(lastSyncExtensionsMap?.get(key)).installed) {
        continue;
      }
      newRemoteExtensionsMap.delete(key);
    }
  }
  const remote = [];
  const remoteChanges = compare3(remoteExtensionsMap, newRemoteExtensionsMap, /* @__PURE__ */ new Set(), true);
  const hasRemoteChanges = remoteChanges.added.size > 0 || remoteChanges.updated.size > 0 || remoteChanges.removed.size > 0;
  if (hasRemoteChanges) {
    newRemoteExtensionsMap.forEach((value, key) => remote.push(massageOutgoingExtension(value, key)));
  }
  return {
    local: { added, removed, updated },
    remote: hasRemoteChanges ? {
      added: [...remoteChanges.added].map((id2) => newRemoteExtensionsMap.get(id2)),
      updated: [...remoteChanges.updated].map((id2) => newRemoteExtensionsMap.get(id2)),
      removed: [...remoteChanges.removed].map((id2) => remoteExtensionsMap.get(id2)),
      all: remote
    } : null
  };
}
function compare3(from, to, ignoredExtensions, checkVersionProperty) {
  const fromKeys = from ? [...from.keys()].filter((key) => !ignoredExtensions.has(key)) : [];
  const toKeys = [...to.keys()].filter((key) => !ignoredExtensions.has(key));
  const added = toKeys.filter((key) => !fromKeys.includes(key)).reduce((r, key) => {
    r.add(key);
    return r;
  }, /* @__PURE__ */ new Set());
  const removed = fromKeys.filter((key) => !toKeys.includes(key)).reduce((r, key) => {
    r.add(key);
    return r;
  }, /* @__PURE__ */ new Set());
  const updated = /* @__PURE__ */ new Set();
  for (const key of fromKeys) {
    if (removed.has(key)) {
      continue;
    }
    const fromExtension = from.get(key);
    const toExtension2 = to.get(key);
    if (!toExtension2 || !areSame(fromExtension, toExtension2, checkVersionProperty, true)) {
      updated.add(key);
    }
  }
  return { added, removed, updated };
}
function areSame(fromExtension, toExtension2, checkVersionProperty, checkInstalledProperty) {
  if (fromExtension.disabled !== toExtension2.disabled) {
    return false;
  }
  if (!!fromExtension.isApplicationScoped !== !!toExtension2.isApplicationScoped) {
    return false;
  }
  if (checkInstalledProperty && fromExtension.installed !== toExtension2.installed) {
    return false;
  }
  if (fromExtension.installed && toExtension2.installed) {
    if (fromExtension.preRelease !== toExtension2.preRelease) {
      return false;
    }
    if (fromExtension.pinned !== toExtension2.pinned) {
      return false;
    }
    if (toExtension2.pinned && fromExtension.version !== toExtension2.version) {
      return false;
    }
  }
  if (!isSameExtensionState(fromExtension.state, toExtension2.state)) {
    return false;
  }
  if (checkVersionProperty && fromExtension.version !== toExtension2.version) {
    return false;
  }
  return true;
}
function mergeExtensionState(localExtension, remoteExtension, lastSyncExtension) {
  const localState = localExtension.state;
  const remoteState = remoteExtension.state;
  const baseState = lastSyncExtension?.state;
  if (!remoteExtension.version) {
    return localState;
  }
  if (localState && gt(localExtension.version, remoteExtension.version)) {
    return localState;
  }
  if (remoteState && gt(remoteExtension.version, localExtension.version)) {
    return remoteState;
  }
  if (!localState) {
    return remoteState;
  }
  if (!remoteState) {
    return localState;
  }
  const mergedState = $zo(localState);
  const baseToRemote = baseState ? compareExtensionState(baseState, remoteState) : { added: Object.keys(remoteState).reduce((r, k) => {
    r.add(k);
    return r;
  }, /* @__PURE__ */ new Set()), removed: /* @__PURE__ */ new Set(), updated: /* @__PURE__ */ new Set() };
  const baseToLocal = baseState ? compareExtensionState(baseState, localState) : { added: Object.keys(localState).reduce((r, k) => {
    r.add(k);
    return r;
  }, /* @__PURE__ */ new Set()), removed: /* @__PURE__ */ new Set(), updated: /* @__PURE__ */ new Set() };
  for (const key of [...baseToRemote.added.values(), ...baseToRemote.updated.values()]) {
    mergedState[key] = remoteState[key];
  }
  for (const key of baseToRemote.removed.values()) {
    if (!baseToLocal.updated.has(key)) {
      delete mergedState[key];
    }
  }
  return mergedState;
}
function compareExtensionState(from, to) {
  const fromKeys = Object.keys(from);
  const toKeys = Object.keys(to);
  const added = toKeys.filter((key) => !fromKeys.includes(key)).reduce((r, key) => {
    r.add(key);
    return r;
  }, /* @__PURE__ */ new Set());
  const removed = fromKeys.filter((key) => !toKeys.includes(key)).reduce((r, key) => {
    r.add(key);
    return r;
  }, /* @__PURE__ */ new Set());
  const updated = /* @__PURE__ */ new Set();
  for (const key of fromKeys) {
    if (removed.has(key)) {
      continue;
    }
    const value1 = from[key];
    const value2 = to[key];
    if (!$Do(value1, value2)) {
      updated.add(key);
    }
  }
  return { added, removed, updated };
}
function isSameExtensionState(a = {}, b = {}) {
  const { added, removed, updated } = compareExtensionState(a, b);
  return added.size === 0 && removed.size === 0 && updated.size === 0;
}
function massageIncomingExtension(extension) {
  return { ...extension, ...{ disabled: !!extension.disabled, installed: !!extension.installed } };
}
function massageOutgoingExtension(extension, key) {
  const massagedExtension = {
    ...extension,
    identifier: {
      id: extension.identifier.id,
      uuid: key.startsWith("uuid:") ? key.substring("uuid:".length) : void 0
    },
    /* set following always so that to differentiate with older clients */
    preRelease: !!extension.preRelease,
    pinned: !!extension.pinned
  };
  if (!extension.disabled) {
    delete massagedExtension.disabled;
  }
  if (!extension.installed) {
    delete massagedExtension.installed;
  }
  if (!extension.state) {
    delete massagedExtension.state;
  }
  if (!extension.isApplicationScoped) {
    delete massagedExtension.isApplicationScoped;
  }
  return massagedExtension;
}

// out-build/vs/platform/userDataProfile/common/userDataProfileStorageService.js
var $gSb = $Zi("IUserDataProfileStorageService");
var $hSb = class $hSb2 extends $0c {
  constructor(persistStorages, b) {
    super();
    this.b = b;
    if (persistStorages) {
      this.a = this.B(new $gd());
    }
  }
  async readStorageData(profile) {
    return this.withProfileScopedStorageService(profile, async (storageService) => this.c(storageService));
  }
  async updateStorageData(profile, data, target) {
    return this.withProfileScopedStorageService(profile, async (storageService) => this.f(storageService, data, target));
  }
  async withProfileScopedStorageService(profile, fn) {
    if (this.b.hasScope(profile)) {
      return fn(this.b);
    }
    let storageService = this.a?.get(profile.id);
    if (!storageService) {
      storageService = new StorageService(this.g(profile));
      this.a?.set(profile.id, storageService);
      try {
        await storageService.initialize();
      } catch (error) {
        if (this.a?.has(profile.id)) {
          this.a.deleteAndDispose(profile.id);
        } else {
          storageService.dispose();
        }
        throw error;
      }
    }
    try {
      const result = await fn(storageService);
      await storageService.flush();
      return result;
    } finally {
      if (!this.a?.has(profile.id)) {
        storageService.dispose();
      }
    }
  }
  c(storageService) {
    const result = /* @__PURE__ */ new Map();
    const populate = (target) => {
      for (const key of storageService.keys(0, target)) {
        result.set(key, { value: storageService.get(
          key,
          0
          /* StorageScope.PROFILE */
        ), target });
      }
    };
    populate(
      0
      /* StorageTarget.USER */
    );
    populate(
      1
      /* StorageTarget.MACHINE */
    );
    return result;
  }
  f(storageService, items, target) {
    storageService.storeAll(Array.from(items.entries()).map(([key, value]) => ({ key, value, scope: 0, target })), true);
  }
};
$hSb = __decorate([
  __param(1, $Dq)
], $hSb);
var $iSb = class extends $hSb {
  constructor(persistStorages, j, userDataProfilesService, storageService, logService) {
    super(persistStorages, storageService);
    this.j = j;
    const channel = j.getChannel("profileStorageListener");
    const disposable = this.B(new $$c());
    this.h = this.B(new $De({
      // Start listening to profile storage changes only when someone is listening
      onWillAddFirstListener: () => {
        disposable.value = channel.listen("onDidChange")((e) => {
          logService.trace("profile storage changes", e);
          this.h.fire({
            targetChanges: e.targetChanges.map((profile) => $8l(profile, userDataProfilesService.profilesHome.scheme)),
            valueChanges: e.valueChanges.map((e2) => ({ ...e2, profile: $8l(e2.profile, userDataProfilesService.profilesHome.scheme) }))
          });
        });
      },
      // Stop listening to profile storage changes when no one is listening
      onDidRemoveLastListener: () => disposable.value = void 0
    }));
    this.onDidChange = this.h.event;
  }
  async g(profile) {
    const storageChannel = this.j.getChannel("storage");
    return $Gq(profile) ? new $cSb(storageChannel) : new $dSb(storageChannel, profile);
  }
};
var StorageService = class extends $Fq {
  constructor(U) {
    super({ flushInterval: 100 });
    this.U = U;
  }
  async O() {
    const profileStorageDatabase = await this.U;
    const profileStorage = new $zq(profileStorageDatabase);
    this.B(profileStorage.onDidChangeStorage((e) => {
      this.u(0, e);
    }));
    this.B($8c(() => {
      profileStorage.close();
      profileStorage.dispose();
      if ($4c(profileStorageDatabase)) {
        profileStorageDatabase.dispose();
      }
    }));
    this.s = profileStorage;
    return this.s.init();
  }
  P(scope) {
    return scope === 0 ? this.s : void 0;
  }
  Q() {
    return void 0;
  }
  async R() {
  }
  async S() {
  }
  hasScope() {
    return false;
  }
};

// out-build/vs/platform/userDataSync/common/extensionsSync.js
async function parseAndMigrateExtensions(syncData, extensionManagementService) {
  const extensions = JSON.parse(syncData.content);
  if (syncData.version === 1 || syncData.version === 2) {
    const builtinExtensions = (await extensionManagementService.getInstalled(
      0
      /* ExtensionType.System */
    )).filter((e) => e.isBuiltin);
    for (const extension of extensions) {
      if (syncData.version === 1) {
        if (extension.enabled === false) {
          extension.disabled = true;
        }
        delete extension.enabled;
      }
      if (syncData.version === 2) {
        if (builtinExtensions.every((installed) => !$8p(installed.identifier, extension.identifier))) {
          extension.installed = true;
        }
      }
    }
  }
  return extensions;
}
function $Rgc(syncData) {
  return JSON.parse(syncData.content);
}
function $Sgc(extensions, format2) {
  extensions.sort((e1, e2) => {
    if (!e1.identifier.uuid && e2.identifier.uuid) {
      return -1;
    }
    if (e1.identifier.uuid && !e2.identifier.uuid) {
      return 1;
    }
    return $Sf(e1.identifier.id, e2.identifier.id);
  });
  return format2 ? $ro(extensions, {}) : JSON.stringify(extensions);
}
var $Tgc = class $Tgc2 extends $iTb {
  constructor(profile, collection, environmentService, fileService, storageService, userDataSyncStoreService, userDataSyncLocalStoreService, Cb, Db, logService, configurationService, userDataSyncEnablementService, telemetryService, extensionStorageService, uriIdentityService, userDataProfileStorageService, Eb) {
    super({ syncResource: "extensions", profile }, collection, fileService, environmentService, storageService, userDataSyncStoreService, userDataSyncLocalStoreService, userDataSyncEnablementService, telemetryService, logService, configurationService, uriIdentityService);
    this.Cb = Cb;
    this.Db = Db;
    this.Eb = Eb;
    this.pb = 6;
    this.wb = this.h.joinPath(this.g, "extensions.json");
    this.xb = this.wb.with({ scheme: $4rb, authority: "base" });
    this.yb = this.wb.with({ scheme: $4rb, authority: "local" });
    this.zb = this.wb.with({ scheme: $4rb, authority: "remote" });
    this.Ab = this.wb.with({ scheme: $4rb, authority: "accepted" });
    this.Bb = this.Eb.createInstance($Ugc);
    this.B(Event.any(Event.filter(this.Cb.onDidInstallExtensions, (e) => e.some(({ local }) => !!local)), Event.filter(this.Cb.onDidUninstallExtension, (e) => !e.error), Event.filter(userDataProfileStorageService.onDidChange, (e) => e.valueChanges.some(({ profile: profile2, changes }) => this.syncResource.profile.id === profile2.id && changes.some((change) => change.key === $Kp))), extensionStorageService.onDidChangeExtensionStorageToSync)(() => this.Q()));
  }
  async qb(remoteUserData, lastSyncUserData) {
    const remoteExtensions = remoteUserData.syncData ? await parseAndMigrateExtensions(remoteUserData.syncData, this.Cb) : null;
    const skippedExtensions = lastSyncUserData?.skippedExtensions ?? [];
    const builtinExtensions = lastSyncUserData?.builtinExtensions ?? null;
    const lastSyncExtensions = lastSyncUserData?.syncData ? await parseAndMigrateExtensions(lastSyncUserData.syncData, this.Cb) : null;
    const { localExtensions, ignoredExtensions } = await this.Bb.getLocalExtensions(this.syncResource.profile);
    if (remoteExtensions) {
      this.O.trace(`${this.D}: Merging remote extensions with local extensions...`);
    } else {
      this.O.trace(`${this.D}: Remote extensions does not exist. Synchronizing extensions for the first time.`);
    }
    const { local, remote } = $Qgc(localExtensions, remoteExtensions, lastSyncExtensions, skippedExtensions, ignoredExtensions, builtinExtensions);
    const previewResult = {
      local,
      remote,
      content: this.Hb(localExtensions, local.added, local.updated, local.removed),
      localChange: local.added.length > 0 || local.removed.length > 0 || local.updated.length > 0 ? 2 : 0,
      remoteChange: remote !== null ? 2 : 0
    };
    const localContent = this.Ob(localExtensions, false);
    return [{
      skippedExtensions,
      builtinExtensions,
      baseResource: this.xb,
      baseContent: lastSyncExtensions ? this.Ob(lastSyncExtensions, false) : localContent,
      localResource: this.yb,
      localContent,
      localExtensions,
      remoteResource: this.zb,
      remoteExtensions,
      remoteContent: remoteExtensions ? this.Ob(remoteExtensions, false) : null,
      previewResource: this.wb,
      previewResult,
      localChange: previewResult.localChange,
      remoteChange: previewResult.remoteChange,
      acceptedResource: this.Ab
    }];
  }
  async ub(lastSyncUserData) {
    const lastSyncExtensions = lastSyncUserData.syncData ? await parseAndMigrateExtensions(lastSyncUserData.syncData, this.Cb) : null;
    const { localExtensions, ignoredExtensions } = await this.Bb.getLocalExtensions(this.syncResource.profile);
    const { remote } = $Qgc(localExtensions, lastSyncExtensions, lastSyncExtensions, lastSyncUserData.skippedExtensions || [], ignoredExtensions, lastSyncUserData.builtinExtensions || []);
    return remote !== null;
  }
  Hb(localExtensions, added, updated, removed) {
    const preview = [...added, ...updated];
    const idsOrUUIDs = /* @__PURE__ */ new Set();
    const addIdentifier = (identifier) => {
      idsOrUUIDs.add(identifier.id.toLowerCase());
      if (identifier.uuid) {
        idsOrUUIDs.add(identifier.uuid);
      }
    };
    preview.forEach(({ identifier }) => addIdentifier(identifier));
    removed.forEach(addIdentifier);
    for (const localExtension of localExtensions) {
      if (idsOrUUIDs.has(localExtension.identifier.id.toLowerCase()) || localExtension.identifier.uuid && idsOrUUIDs.has(localExtension.identifier.uuid)) {
        continue;
      }
      preview.push(localExtension);
    }
    return this.Ob(preview, false);
  }
  async rb(resourcePreview, token) {
    return { ...resourcePreview.previewResult, hasConflicts: false };
  }
  async sb(resourcePreview, resource, content, token) {
    if (this.h.isEqual(resource, this.yb)) {
      return this.Kb(resourcePreview);
    }
    if (this.h.isEqual(resource, this.zb)) {
      return this.Lb(resourcePreview);
    }
    if (this.h.isEqual(resource, this.wb)) {
      return resourcePreview.previewResult;
    }
    throw new Error(`Invalid Resource: ${resource.toString()}`);
  }
  async Kb(resourcePreview) {
    const installedExtensions = await this.Cb.getInstalled(void 0, this.syncResource.profile.extensionsResource);
    const ignoredExtensions = this.Db.getIgnoredExtensions(installedExtensions);
    const mergeResult = $Qgc(resourcePreview.localExtensions, null, null, resourcePreview.skippedExtensions, ignoredExtensions, resourcePreview.builtinExtensions);
    const { local, remote } = mergeResult;
    return {
      content: resourcePreview.localContent,
      local,
      remote,
      localChange: local.added.length > 0 || local.removed.length > 0 || local.updated.length > 0 ? 2 : 0,
      remoteChange: remote !== null ? 2 : 0
    };
  }
  async Lb(resourcePreview) {
    const installedExtensions = await this.Cb.getInstalled(void 0, this.syncResource.profile.extensionsResource);
    const ignoredExtensions = this.Db.getIgnoredExtensions(installedExtensions);
    const remoteExtensions = resourcePreview.remoteContent ? JSON.parse(resourcePreview.remoteContent) : null;
    if (remoteExtensions !== null) {
      const mergeResult = $Qgc(resourcePreview.localExtensions, remoteExtensions, resourcePreview.localExtensions, [], ignoredExtensions, resourcePreview.builtinExtensions);
      const { local, remote } = mergeResult;
      return {
        content: resourcePreview.remoteContent,
        local,
        remote,
        localChange: local.added.length > 0 || local.removed.length > 0 || local.updated.length > 0 ? 2 : 0,
        remoteChange: remote !== null ? 2 : 0
      };
    } else {
      return {
        content: resourcePreview.remoteContent,
        local: { added: [], removed: [], updated: [] },
        remote: null,
        localChange: 0,
        remoteChange: 0
      };
    }
  }
  async tb(remoteUserData, lastSyncUserData, resourcePreviews, force) {
    let { skippedExtensions, builtinExtensions, localExtensions } = resourcePreviews[0][0];
    const { local, remote, localChange, remoteChange } = resourcePreviews[0][1];
    if (localChange === 0 && remoteChange === 0) {
      this.O.info(`${this.D}: No changes found during synchronizing extensions.`);
    }
    if (localChange !== 0) {
      await this.nb(JSON.stringify(localExtensions));
      skippedExtensions = await this.Bb.updateLocalExtensions(local.added, local.removed, local.updated, skippedExtensions, this.syncResource.profile);
    }
    if (remote) {
      this.O.trace(`${this.D}: Updating remote extensions...`);
      const content = JSON.stringify(remote.all);
      remoteUserData = await this.mb(content, force ? null : remoteUserData.ref);
      this.O.info(`${this.D}: Updated remote extensions.${remote.added.length ? ` Added: ${JSON.stringify(remote.added.map((e) => e.identifier.id))}.` : ""}${remote.updated.length ? ` Updated: ${JSON.stringify(remote.updated.map((e) => e.identifier.id))}.` : ""}${remote.removed.length ? ` Removed: ${JSON.stringify(remote.removed.map((e) => e.identifier.id))}.` : ""}`);
    }
    if (lastSyncUserData?.ref !== remoteUserData.ref) {
      this.O.trace(`${this.D}: Updating last synchronized extensions...`);
      builtinExtensions = this.Nb(localExtensions, builtinExtensions);
      await this.fb(remoteUserData, { skippedExtensions, builtinExtensions });
      this.O.info(`${this.D}: Updated last synchronized extensions.${skippedExtensions.length ? ` Skipped: ${JSON.stringify(skippedExtensions.map((e) => e.identifier.id))}.` : ""}`);
    }
  }
  Nb(localExtensions, previousBuiltinExtensions) {
    const localExtensionsSet = /* @__PURE__ */ new Set();
    const builtinExtensions = [];
    for (const localExtension of localExtensions) {
      localExtensionsSet.add(localExtension.identifier.id.toLowerCase());
      if (!localExtension.installed) {
        builtinExtensions.push(localExtension.identifier);
      }
    }
    if (previousBuiltinExtensions) {
      for (const builtinExtension of previousBuiltinExtensions) {
        if (!localExtensionsSet.has(builtinExtension.id.toLowerCase())) {
          builtinExtensions.push(builtinExtension);
        }
      }
    }
    return builtinExtensions;
  }
  async resolveContent(uri) {
    if (this.h.isEqual(this.zb, uri) || this.h.isEqual(this.xb, uri) || this.h.isEqual(this.yb, uri) || this.h.isEqual(this.Ab, uri)) {
      const content = await this.db(uri);
      return content ? this.Ob(JSON.parse(content), true) : content;
    }
    return null;
  }
  Ob(extensions, format2) {
    return $Sgc(extensions, format2);
  }
  async hasLocalData() {
    try {
      const { localExtensions } = await this.Bb.getLocalExtensions(this.syncResource.profile);
      if (localExtensions.some((e) => e.installed || e.disabled)) {
        return true;
      }
    } catch (error) {
    }
    return false;
  }
};
$Tgc = __decorate([
  __param(2, $7i),
  __param(3, $ul),
  __param(4, $Dq),
  __param(5, $Mrb),
  __param(6, $Nrb),
  __param(7, $Jp),
  __param(8, $aUb),
  __param(9, $2rb),
  __param(10, $tj),
  __param(11, $Wrb),
  __param(12, $tm),
  __param(13, $Yw),
  __param(14, $5l),
  __param(15, $gSb),
  __param(16, $Yi)
], $Tgc);
var $Ugc = class $Ugc2 {
  constructor(a, b, c, d, f, g) {
    this.a = a;
    this.b = b;
    this.c = c;
    this.d = d;
    this.f = f;
    this.g = g;
  }
  async getLocalExtensions(profile) {
    const installedExtensions = await this.a.getInstalled(void 0, profile.extensionsResource);
    const ignoredExtensions = this.d.getIgnoredExtensions(installedExtensions);
    const localExtensions = await this.j(profile, async (extensionEnablementService, extensionStorageService) => {
      const disabledExtensions = extensionEnablementService.getDisabledExtensions();
      return installedExtensions.map((extension) => {
        const { identifier, isBuiltin, manifest, preRelease, pinned, isApplicationScoped } = extension;
        const syncExntesion = { identifier, preRelease, version: manifest.version, pinned: !!pinned };
        if (isApplicationScoped && !$Pn(manifest)) {
          syncExntesion.isApplicationScoped = isApplicationScoped;
        }
        if (disabledExtensions.some((disabledExtension) => $8p(disabledExtension, identifier))) {
          syncExntesion.disabled = true;
        }
        if (!isBuiltin) {
          syncExntesion.installed = true;
        }
        try {
          const keys = extensionStorageService.getKeysForSync({ id: identifier.id, version: manifest.version });
          if (keys) {
            const extensionStorageState = extensionStorageService.getExtensionState(extension, true) || {};
            syncExntesion.state = Object.keys(extensionStorageState).reduce((state, key) => {
              if (keys.includes(key)) {
                state[key] = extensionStorageState[key];
              }
              return state;
            }, {});
          }
        } catch (error) {
          this.g.info(`${$hTb("extensions", profile)}: Error while parsing extension state`, $kb(error));
        }
        return syncExntesion;
      });
    });
    return { localExtensions, ignoredExtensions };
  }
  async updateLocalExtensions(added, removed, updated, skippedExtensions, profile) {
    const syncResourceLogLabel = $hTb("extensions", profile);
    const extensionsToInstall = [];
    const syncExtensionsToInstall = /* @__PURE__ */ new Map();
    const removeFromSkipped = [];
    const addToSkipped = [];
    const installedExtensions = await this.a.getInstalled(void 0, profile.extensionsResource);
    if (added.length || updated.length) {
      await this.j(profile, async (extensionEnablementService, extensionStorageService) => {
        await Promises.settled([...added, ...updated].map(async (e) => {
          const installedExtension = installedExtensions.find((installed) => $8p(installed.identifier, e.identifier));
          if (installedExtension && installedExtension.isBuiltin) {
            if (e.state && installedExtension.manifest.version === e.version) {
              this.h(e.state, installedExtension, installedExtension.manifest.version, extensionStorageService);
            }
            const isDisabled = extensionEnablementService.getDisabledExtensions().some((disabledExtension) => $8p(disabledExtension, e.identifier));
            if (isDisabled !== !!e.disabled) {
              if (e.disabled) {
                this.g.trace(`${syncResourceLogLabel}: Disabling extension...`, e.identifier.id);
                await extensionEnablementService.disableExtension(e.identifier);
                this.g.info(`${syncResourceLogLabel}: Disabled extension`, e.identifier.id);
              } else {
                this.g.trace(`${syncResourceLogLabel}: Enabling extension...`, e.identifier.id);
                await extensionEnablementService.enableExtension(e.identifier);
                this.g.info(`${syncResourceLogLabel}: Enabled extension`, e.identifier.id);
              }
            }
            removeFromSkipped.push(e.identifier);
            return;
          }
          const version = e.pinned ? e.version : void 0;
          const extension = (await this.c.getExtensions([{ ...e.identifier, version, preRelease: version ? void 0 : e.preRelease }], CancellationToken.None))[0];
          if (e.state && (installedExtension ? installedExtension.manifest.version === e.version : !!extension)) {
            this.h(e.state, installedExtension || extension, installedExtension?.manifest.version, extensionStorageService);
          }
          if (extension) {
            try {
              const isDisabled = extensionEnablementService.getDisabledExtensions().some((disabledExtension) => $8p(disabledExtension, e.identifier));
              if (isDisabled !== !!e.disabled) {
                if (e.disabled) {
                  this.g.trace(`${syncResourceLogLabel}: Disabling extension...`, e.identifier.id, extension.version);
                  await extensionEnablementService.disableExtension(extension.identifier);
                  this.g.info(`${syncResourceLogLabel}: Disabled extension`, e.identifier.id, extension.version);
                } else {
                  this.g.trace(`${syncResourceLogLabel}: Enabling extension...`, e.identifier.id, extension.version);
                  await extensionEnablementService.enableExtension(extension.identifier);
                  this.g.info(`${syncResourceLogLabel}: Enabled extension`, e.identifier.id, extension.version);
                }
              }
              if (!installedExtension || installedExtension.preRelease !== e.preRelease || installedExtension.pinned !== e.pinned || version && installedExtension.manifest.version !== version) {
                if (await this.a.canInstall(extension)) {
                  extensionsToInstall.push({
                    extension,
                    options: {
                      isMachineScoped: false,
                      donotIncludePackAndDependencies: true,
                      installGivenVersion: e.pinned && !!e.version,
                      pinned: e.pinned,
                      installPreReleaseVersion: e.preRelease,
                      profileLocation: profile.extensionsResource,
                      isApplicationScoped: e.isApplicationScoped,
                      context: {
                        [$wp]: true,
                        [$xp]: "settingsSync"
                        /* ExtensionInstallSource.SETTINGS_SYNC */
                      }
                    }
                  });
                  syncExtensionsToInstall.set(extension.identifier.id.toLowerCase(), e);
                } else {
                  this.g.info(`${syncResourceLogLabel}: Skipped synchronizing extension because it cannot be installed.`, extension.displayName || extension.identifier.id);
                  addToSkipped.push(e);
                }
              }
            } catch (error) {
              addToSkipped.push(e);
              this.g.error(error);
              this.g.info(`${syncResourceLogLabel}: Skipped synchronizing extension`, extension.displayName || extension.identifier.id);
            }
          } else {
            addToSkipped.push(e);
            this.g.info(`${syncResourceLogLabel}: Skipped synchronizing extension because the extension is not found.`, e.identifier.id);
          }
        }));
      });
    }
    if (removed.length) {
      const extensionsToRemove = installedExtensions.filter(({ identifier, isBuiltin }) => !isBuiltin && removed.some((r) => $8p(identifier, r)));
      await Promises.settled(extensionsToRemove.map(async (extensionToRemove) => {
        this.g.trace(`${syncResourceLogLabel}: Uninstalling local extension...`, extensionToRemove.identifier.id);
        await this.a.uninstall(extensionToRemove, { donotIncludePack: true, donotCheckDependents: true, profileLocation: profile.extensionsResource });
        this.g.info(`${syncResourceLogLabel}: Uninstalled local extension.`, extensionToRemove.identifier.id);
        removeFromSkipped.push(extensionToRemove.identifier);
      }));
    }
    const results = await this.a.installGalleryExtensions(extensionsToInstall);
    for (const { identifier, local, error, source } of results) {
      const gallery = source;
      if (local) {
        this.g.info(`${syncResourceLogLabel}: Installed extension.`, identifier.id, gallery.version);
        removeFromSkipped.push(identifier);
      } else {
        const e = syncExtensionsToInstall.get(identifier.id.toLowerCase());
        if (e) {
          addToSkipped.push(e);
          this.g.info(`${syncResourceLogLabel}: Skipped synchronizing extension`, gallery.displayName || gallery.identifier.id);
        }
        if (error instanceof $Ip && [
          "Incompatible",
          "IncompatibleApi",
          "IncompatibleTargetPlatform"
          /* ExtensionManagementErrorCode.IncompatibleTargetPlatform */
        ].includes(error.code)) {
          this.g.info(`${syncResourceLogLabel}: Skipped synchronizing extension because the compatible extension is not found.`, gallery.displayName || gallery.identifier.id);
        } else if (error) {
          this.g.error(error);
        }
      }
    }
    const newSkippedExtensions = [];
    for (const skippedExtension of skippedExtensions) {
      if (!removeFromSkipped.some((e) => $8p(e, skippedExtension.identifier))) {
        newSkippedExtensions.push(skippedExtension);
      }
    }
    for (const skippedExtension of addToSkipped) {
      if (!newSkippedExtensions.some((e) => $8p(e.identifier, skippedExtension.identifier))) {
        newSkippedExtensions.push(skippedExtension);
      }
    }
    return newSkippedExtensions;
  }
  h(state, extension, version, extensionStorageService) {
    const extensionState = extensionStorageService.getExtensionState(extension, true) || {};
    const keys = version ? extensionStorageService.getKeysForSync({ id: extension.identifier.id, version }) : void 0;
    if (keys) {
      keys.forEach((key) => {
        extensionState[key] = state[key];
      });
    } else {
      Object.keys(state).forEach((key) => extensionState[key] = state[key]);
    }
    extensionStorageService.setExtensionState(extension, extensionState, true);
  }
  async j(profile, fn) {
    return this.b.withProfileScopedStorageService(profile, async (storageService) => {
      const disposables = new $9c();
      const instantiationService = disposables.add(this.f.createChild(new $Xi([$Dq, storageService])));
      const extensionEnablementService = disposables.add(instantiationService.createInstance($ERb));
      const extensionStorageService = disposables.add(instantiationService.createInstance($Zw));
      try {
        return await fn(extensionEnablementService, extensionStorageService);
      } finally {
        disposables.dispose();
      }
    });
  }
};
$Ugc = __decorate([
  __param(0, $Jp),
  __param(1, $gSb),
  __param(2, $Gp),
  __param(3, $aUb),
  __param(4, $Yi),
  __param(5, $2rb)
], $Ugc);
var $Vgc = class $Vgc2 extends $lTb {
  constructor(p, q, fileService, userDataProfilesService, environmentService, logService, storageService, uriIdentityService) {
    super("extensions", userDataProfilesService, environmentService, logService, fileService, storageService, uriIdentityService);
    this.p = p;
    this.q = q;
  }
  async t(remoteUserData) {
    return remoteUserData.syncData ? await parseAndMigrateExtensions(remoteUserData.syncData, this.p) : null;
  }
  u(remoteExtensions, localExtensions) {
    const installedExtensions = [];
    const newExtensions = [];
    const disabledExtensions = [];
    for (const extension of remoteExtensions) {
      if (this.q.hasToNeverSyncExtension(extension.identifier.id)) {
        continue;
      }
      const installedExtension = localExtensions.find((i) => $8p(i.identifier, extension.identifier));
      if (installedExtension) {
        installedExtensions.push(installedExtension);
        if (extension.disabled) {
          disabledExtensions.push(extension.identifier);
        }
      } else if (extension.installed) {
        newExtensions.push({ ...extension.identifier, preRelease: !!extension.preRelease });
        if (extension.disabled) {
          disabledExtensions.push(extension.identifier);
        }
      }
    }
    return { installedExtensions, newExtensions, disabledExtensions, remoteExtensions };
  }
};
$Vgc = __decorate([
  __param(0, $Jp),
  __param(1, $aUb),
  __param(2, $ul),
  __param(3, $7l),
  __param(4, $7i),
  __param(5, $uk),
  __param(6, $Dq),
  __param(7, $5l)
], $Vgc);

// out-build/vs/platform/userDataSync/common/content.js
function edit(content, originalPath, value, formattingOptions) {
  const edit2 = $vo(content, originalPath, value, formattingOptions)[0];
  if (edit2) {
    content = content.substring(0, edit2.offset) + edit2.content + content.substring(edit2.offset + edit2.length);
  }
  return content;
}

// out-build/vs/platform/userDataSync/common/globalStateMerge.js
function $mTb(localStorage, remoteStorage, baseStorage, storageKeys, logService) {
  if (!remoteStorage) {
    return { remote: { added: Object.keys(localStorage), removed: [], updated: [], all: Object.keys(localStorage).length > 0 ? localStorage : null }, local: { added: {}, removed: [], updated: {} } };
  }
  const localToRemote = compare4(localStorage, remoteStorage);
  if (localToRemote.added.size === 0 && localToRemote.removed.size === 0 && localToRemote.updated.size === 0) {
    return { remote: { added: [], removed: [], updated: [], all: null }, local: { added: {}, removed: [], updated: {} } };
  }
  const baseToRemote = baseStorage ? compare4(baseStorage, remoteStorage) : { added: Object.keys(remoteStorage).reduce((r, k) => {
    r.add(k);
    return r;
  }, /* @__PURE__ */ new Set()), removed: /* @__PURE__ */ new Set(), updated: /* @__PURE__ */ new Set() };
  const baseToLocal = baseStorage ? compare4(baseStorage, localStorage) : { added: Object.keys(localStorage).reduce((r, k) => {
    r.add(k);
    return r;
  }, /* @__PURE__ */ new Set()), removed: /* @__PURE__ */ new Set(), updated: /* @__PURE__ */ new Set() };
  const local = { added: {}, removed: [], updated: {} };
  const remote = $zo(remoteStorage);
  const isFirstTimeSync = !baseStorage;
  for (const key of baseToLocal.added.values()) {
    if (key !== $Urb && isFirstTimeSync && baseToRemote.added.has(key)) {
      continue;
    }
    remote[key] = localStorage[key];
  }
  for (const key of baseToLocal.updated.values()) {
    remote[key] = localStorage[key];
  }
  for (const key of baseToLocal.removed.values()) {
    if (storageKeys.unregistered.includes(key)) {
      continue;
    }
    delete remote[key];
  }
  for (const key of baseToRemote.added.values()) {
    const remoteValue = remoteStorage[key];
    if (storageKeys.machine.includes(key)) {
      logService.info(`GlobalState: Skipped adding ${key} in local storage because it is declared as machine scoped.`);
      continue;
    }
    if (baseStorage && baseToLocal.added.has(key)) {
      continue;
    }
    const localValue = localStorage[key];
    if (localValue && localValue.value === remoteValue.value) {
      continue;
    }
    if (key === $Urb && isFirstTimeSync && baseToLocal.added.has(key)) {
      continue;
    }
    if (localValue) {
      local.updated[key] = remoteValue;
    } else {
      local.added[key] = remoteValue;
    }
  }
  for (const key of baseToRemote.updated.values()) {
    const remoteValue = remoteStorage[key];
    if (storageKeys.machine.includes(key)) {
      logService.info(`GlobalState: Skipped updating ${key} in local storage because it is declared as machine scoped.`);
      continue;
    }
    if (baseToLocal.updated.has(key) || baseToLocal.removed.has(key)) {
      continue;
    }
    const localValue = localStorage[key];
    if (localValue && localValue.value === remoteValue.value) {
      continue;
    }
    local.updated[key] = remoteValue;
  }
  for (const key of baseToRemote.removed.values()) {
    if (storageKeys.machine.includes(key)) {
      logService.trace(`GlobalState: Skipped removing ${key} in local storage because it is declared as machine scoped.`);
      continue;
    }
    if (baseToLocal.updated.has(key) || baseToLocal.removed.has(key)) {
      continue;
    }
    local.removed.push(key);
  }
  const result = compare4(remoteStorage, remote);
  return { local, remote: { added: [...result.added], updated: [...result.updated], removed: [...result.removed], all: result.added.size === 0 && result.removed.size === 0 && result.updated.size === 0 ? null : remote } };
}
function compare4(from, to) {
  const fromKeys = Object.keys(from);
  const toKeys = Object.keys(to);
  const added = toKeys.filter((key) => !fromKeys.includes(key)).reduce((r, key) => {
    r.add(key);
    return r;
  }, /* @__PURE__ */ new Set());
  const removed = fromKeys.filter((key) => !toKeys.includes(key)).reduce((r, key) => {
    r.add(key);
    return r;
  }, /* @__PURE__ */ new Set());
  const updated = /* @__PURE__ */ new Set();
  for (const key of fromKeys) {
    if (removed.has(key)) {
      continue;
    }
    const value1 = from[key];
    const value2 = to[key];
    if (!$Do(value1, value2)) {
      updated.add(key);
    }
  }
  return { added, removed, updated };
}

// out-build/vs/platform/userDataSync/common/globalStateSync.js
var argvStoragePrefx = "globalState.argv.";
var argvProperties = ["locale"];
function $nTb(globalState, format2) {
  const storageKeys = globalState.storage ? Object.keys(globalState.storage).sort() : [];
  const storage = {};
  storageKeys.forEach((key) => storage[key] = globalState.storage[key]);
  globalState.storage = storage;
  return format2 ? $ro(globalState, {}) : JSON.stringify(globalState);
}
var GLOBAL_STATE_DATA_VERSION = 1;
var $oTb = class $oTb2 extends $iTb {
  constructor(profile, collection, Bb, fileService, userDataSyncStoreService, userDataSyncLocalStoreService, logService, environmentService, userDataSyncEnablementService, telemetryService, configurationService, storageService, uriIdentityService, instantiationService) {
    super({ syncResource: "globalState", profile }, collection, fileService, environmentService, storageService, userDataSyncStoreService, userDataSyncLocalStoreService, userDataSyncEnablementService, telemetryService, logService, configurationService, uriIdentityService);
    this.Bb = Bb;
    this.pb = GLOBAL_STATE_DATA_VERSION;
    this.vb = this.h.joinPath(this.g, "globalState.json");
    this.wb = this.vb.with({ scheme: $4rb, authority: "base" });
    this.xb = this.vb.with({ scheme: $4rb, authority: "local" });
    this.yb = this.vb.with({ scheme: $4rb, authority: "remote" });
    this.zb = this.vb.with({ scheme: $4rb, authority: "accepted" });
    this.Ab = instantiationService.createInstance($pTb);
    this.B(fileService.watch(this.h.dirname(this.H.argvResource)));
    this.B(Event.any(
      /* Locale change */
      Event.filter(fileService.onDidFilesChange, (e) => e.contains(this.H.argvResource)),
      Event.filter(Bb.onDidChange, (e) => {
        if (e.targetChanges.some((profile2) => this.syncResource.profile.id === profile2.id)) {
          return true;
        }
        if (e.valueChanges.some(({ profile: profile2, changes }) => this.syncResource.profile.id === profile2.id && changes.some(
          (change) => change.target === 0
          /* StorageTarget.USER */
        ))) {
          return true;
        }
        return false;
      })
    )(() => this.Q()));
  }
  async qb(remoteUserData, lastSyncUserData, isRemoteDataFromCurrentMachine) {
    const remoteGlobalState = remoteUserData.syncData ? JSON.parse(remoteUserData.syncData.content) : null;
    lastSyncUserData = lastSyncUserData === null && isRemoteDataFromCurrentMachine ? remoteUserData : lastSyncUserData;
    const lastSyncGlobalState = lastSyncUserData && lastSyncUserData.syncData ? JSON.parse(lastSyncUserData.syncData.content) : null;
    const localGlobalState = await this.Ab.getLocalGlobalState(this.syncResource.profile);
    if (remoteGlobalState) {
      this.O.trace(`${this.D}: Merging remote ui state with local ui state...`);
    } else {
      this.O.trace(`${this.D}: Remote ui state does not exist. Synchronizing ui state for the first time.`);
    }
    const storageKeys = await this.Jb(lastSyncGlobalState);
    const { local, remote } = $mTb(localGlobalState.storage, remoteGlobalState ? remoteGlobalState.storage : null, lastSyncGlobalState ? lastSyncGlobalState.storage : null, storageKeys, this.O);
    const previewResult = {
      content: null,
      local,
      remote,
      localChange: Object.keys(local.added).length > 0 || Object.keys(local.updated).length > 0 || local.removed.length > 0 ? 2 : 0,
      remoteChange: remote.all !== null ? 2 : 0
    };
    const localContent = $nTb(localGlobalState, false);
    return [{
      baseResource: this.wb,
      baseContent: lastSyncGlobalState ? $nTb(lastSyncGlobalState, false) : localContent,
      localResource: this.xb,
      localContent,
      localUserData: localGlobalState,
      remoteResource: this.yb,
      remoteContent: remoteGlobalState ? $nTb(remoteGlobalState, false) : null,
      previewResource: this.vb,
      previewResult,
      localChange: previewResult.localChange,
      remoteChange: previewResult.remoteChange,
      acceptedResource: this.zb,
      storageKeys
    }];
  }
  async ub(lastSyncUserData) {
    const lastSyncGlobalState = lastSyncUserData.syncData ? JSON.parse(lastSyncUserData.syncData.content) : null;
    if (lastSyncGlobalState === null) {
      return true;
    }
    const localGlobalState = await this.Ab.getLocalGlobalState(this.syncResource.profile);
    const storageKeys = await this.Jb(lastSyncGlobalState);
    const { remote } = $mTb(localGlobalState.storage, lastSyncGlobalState.storage, lastSyncGlobalState.storage, storageKeys, this.O);
    return remote.all !== null;
  }
  async rb(resourcePreview, token) {
    return { ...resourcePreview.previewResult, hasConflicts: false };
  }
  async sb(resourcePreview, resource, content, token) {
    if (this.h.isEqual(resource, this.xb)) {
      return this.Gb(resourcePreview);
    }
    if (this.h.isEqual(resource, this.yb)) {
      return this.Hb(resourcePreview);
    }
    if (this.h.isEqual(resource, this.vb)) {
      return resourcePreview.previewResult;
    }
    throw new Error(`Invalid Resource: ${resource.toString()}`);
  }
  async Gb(resourcePreview) {
    return {
      content: resourcePreview.localContent,
      local: { added: {}, removed: [], updated: {} },
      remote: { added: Object.keys(resourcePreview.localUserData.storage), removed: [], updated: [], all: resourcePreview.localUserData.storage },
      localChange: 0,
      remoteChange: 2
    };
  }
  async Hb(resourcePreview) {
    if (resourcePreview.remoteContent !== null) {
      const remoteGlobalState = JSON.parse(resourcePreview.remoteContent);
      const { local, remote } = $mTb(resourcePreview.localUserData.storage, remoteGlobalState.storage, null, resourcePreview.storageKeys, this.O);
      return {
        content: resourcePreview.remoteContent,
        local,
        remote,
        localChange: Object.keys(local.added).length > 0 || Object.keys(local.updated).length > 0 || local.removed.length > 0 ? 2 : 0,
        remoteChange: remote !== null ? 2 : 0
      };
    } else {
      return {
        content: resourcePreview.remoteContent,
        local: { added: {}, removed: [], updated: {} },
        remote: { added: [], removed: [], updated: [], all: null },
        localChange: 0,
        remoteChange: 0
      };
    }
  }
  async tb(remoteUserData, lastSyncUserData, resourcePreviews, force) {
    const { localUserData } = resourcePreviews[0][0];
    const { local, remote, localChange, remoteChange } = resourcePreviews[0][1];
    if (localChange === 0 && remoteChange === 0) {
      this.O.info(`${this.D}: No changes found during synchronizing ui state.`);
    }
    if (localChange !== 0) {
      this.O.trace(`${this.D}: Updating local ui state...`);
      await this.nb(JSON.stringify(localUserData));
      await this.Ab.writeLocalGlobalState(local, this.syncResource.profile);
      this.O.info(`${this.D}: Updated local ui state`);
    }
    if (remoteChange !== 0) {
      this.O.trace(`${this.D}: Updating remote ui state...`);
      const content = JSON.stringify({ storage: remote.all });
      remoteUserData = await this.mb(content, force ? null : remoteUserData.ref);
      this.O.info(`${this.D}: Updated remote ui state.${remote.added.length ? ` Added: ${remote.added}.` : ""}${remote.updated.length ? ` Updated: ${remote.updated}.` : ""}${remote.removed.length ? ` Removed: ${remote.removed}.` : ""}`);
    }
    if (lastSyncUserData?.ref !== remoteUserData.ref) {
      this.O.trace(`${this.D}: Updating last synchronized ui state...`);
      await this.fb(remoteUserData);
      this.O.info(`${this.D}: Updated last synchronized ui state`);
    }
  }
  async resolveContent(uri) {
    if (this.h.isEqual(this.yb, uri) || this.h.isEqual(this.wb, uri) || this.h.isEqual(this.xb, uri) || this.h.isEqual(this.zb, uri)) {
      const content = await this.db(uri);
      return content ? $nTb(JSON.parse(content), true) : content;
    }
    return null;
  }
  async hasLocalData() {
    try {
      const { storage } = await this.Ab.getLocalGlobalState(this.syncResource.profile);
      if (Object.keys(storage).length > 1 || storage[`${argvStoragePrefx}.locale`]?.value !== "en") {
        return true;
      }
    } catch (error) {
    }
    return false;
  }
  async Jb(lastSyncGlobalState) {
    const storageData = await this.Bb.readStorageData(this.syncResource.profile);
    const user = [], machine = [];
    for (const [key, value] of storageData) {
      if (value.target === 0) {
        user.push(key);
      } else if (value.target === 1) {
        machine.push(key);
      }
    }
    const registered = [...user, ...machine];
    const unregistered = lastSyncGlobalState?.storage ? Object.keys(lastSyncGlobalState.storage).filter((key) => !key.startsWith(argvStoragePrefx) && !registered.includes(key) && storageData.get(key) !== void 0) : [];
    if (!$r) {
      const keysSyncedOnlyInWeb = [...$Irb.map((resource) => $Vrb(resource)), $Urb];
      unregistered.push(...keysSyncedOnlyInWeb);
      machine.push(...keysSyncedOnlyInWeb);
    }
    return { user, machine, unregistered };
  }
};
$oTb = __decorate([
  __param(2, $gSb),
  __param(3, $ul),
  __param(4, $Mrb),
  __param(5, $Nrb),
  __param(6, $2rb),
  __param(7, $7i),
  __param(8, $Wrb),
  __param(9, $tm),
  __param(10, $tj),
  __param(11, $Dq),
  __param(12, $5l),
  __param(13, $Yi)
], $oTb);
var $pTb = class $pTb2 {
  constructor(a, b, c, d) {
    this.a = a;
    this.b = b;
    this.c = c;
    this.d = d;
  }
  async getLocalGlobalState(profile) {
    const storage = {};
    if (profile.isDefault) {
      const argvContent = await this.f();
      const argvValue = $ho(argvContent);
      for (const argvProperty of argvProperties) {
        if (argvValue[argvProperty] !== void 0) {
          storage[`${argvStoragePrefx}${argvProperty}`] = { version: 1, value: argvValue[argvProperty] };
        }
      }
    }
    const storageData = await this.c.readStorageData(profile);
    for (const [key, value] of storageData) {
      if (value.value && value.target === 0) {
        storage[key] = { version: 1, value: value.value };
      }
    }
    return { storage };
  }
  async f() {
    try {
      this.d.debug("GlobalStateSync#getLocalArgvContent", this.b.argvResource);
      const content = await this.a.readFile(this.b.argvResource);
      this.d.debug("GlobalStateSync#getLocalArgvContent - Resolved", this.b.argvResource);
      return content.value.toString();
    } catch (error) {
      this.d.debug($kb(error));
    }
    return "{}";
  }
  async writeLocalGlobalState({ added, removed, updated }, profile) {
    const syncResourceLogLabel = $hTb("globalState", profile);
    const argv = {};
    const updatedStorage = /* @__PURE__ */ new Map();
    const storageData = await this.c.readStorageData(profile);
    const handleUpdatedStorage = (keys, storage) => {
      for (const key of keys) {
        if (key.startsWith(argvStoragePrefx)) {
          argv[key.substring(argvStoragePrefx.length)] = storage ? storage[key].value : void 0;
          continue;
        }
        if (storage) {
          const storageValue = storage[key];
          if (storageValue.value !== storageData.get(key)?.value) {
            updatedStorage.set(key, storageValue.value);
          }
        } else {
          if (storageData.get(key) !== void 0) {
            updatedStorage.set(key, void 0);
          }
        }
      }
    };
    handleUpdatedStorage(Object.keys(added), added);
    handleUpdatedStorage(Object.keys(updated), updated);
    handleUpdatedStorage(removed);
    if (Object.keys(argv).length) {
      this.d.trace(`${syncResourceLogLabel}: Updating locale...`);
      const argvContent = await this.f();
      let content = argvContent;
      for (const argvProperty of Object.keys(argv)) {
        content = edit(content, [argvProperty], argv[argvProperty], {});
      }
      if (argvContent !== content) {
        this.d.trace(`${syncResourceLogLabel}: Updating locale...`);
        await this.a.writeFile(this.b.argvResource, $7e.fromString(content));
        this.d.info(`${syncResourceLogLabel}: Updated locale.`);
      }
      this.d.info(`${syncResourceLogLabel}: Updated locale`);
    }
    if (updatedStorage.size) {
      this.d.trace(`${syncResourceLogLabel}: Updating global state...`);
      await this.c.updateStorageData(
        profile,
        updatedStorage,
        0
        /* StorageTarget.USER */
      );
      this.d.info(`${syncResourceLogLabel}: Updated global state`, [...updatedStorage.keys()]);
    }
  }
};
$pTb = __decorate([
  __param(0, $ul),
  __param(1, $7i),
  __param(2, $gSb),
  __param(3, $2rb)
], $pTb);
var $qTb = class $qTb2 extends $lTb {
  constructor(storageService, fileService, userDataProfilesService, environmentService, logService, uriIdentityService) {
    super("globalState", userDataProfilesService, environmentService, logService, fileService, storageService, uriIdentityService);
  }
  async o(remoteUserData) {
    const remoteGlobalState = remoteUserData.syncData ? JSON.parse(remoteUserData.syncData.content) : null;
    if (!remoteGlobalState) {
      this.j.info("Skipping initializing global state because remote global state does not exist.");
      return;
    }
    const argv = {};
    const storage = {};
    for (const key of Object.keys(remoteGlobalState.storage)) {
      if (key.startsWith(argvStoragePrefx)) {
        argv[key.substring(argvStoragePrefx.length)] = remoteGlobalState.storage[key].value;
      } else {
        if (this.l.get(
          key,
          0
          /* StorageScope.PROFILE */
        ) === void 0) {
          storage[key] = remoteGlobalState.storage[key].value;
        }
      }
    }
    if (Object.keys(argv).length) {
      let content = "{}";
      try {
        const fileContent = await this.k.readFile(this.h.argvResource);
        content = fileContent.value.toString();
      } catch (error) {
      }
      for (const argvProperty of Object.keys(argv)) {
        content = edit(content, [argvProperty], argv[argvProperty], {});
      }
      await this.k.writeFile(this.h.argvResource, $7e.fromString(content));
    }
    if (Object.keys(storage).length) {
      const storageEntries = [];
      for (const key of Object.keys(storage)) {
        storageEntries.push({
          key,
          value: storage[key],
          scope: 0,
          target: 0
          /* StorageTarget.USER */
        });
      }
      this.l.storeAll(storageEntries, true);
    }
  }
};
$qTb = __decorate([
  __param(0, $Dq),
  __param(1, $ul),
  __param(2, $7l),
  __param(3, $7i),
  __param(4, $2rb),
  __param(5, $5l)
], $qTb);
var $rTb = class $rTb2 {
  constructor(a, b, c, d, f) {
    this.a = a;
    this.b = b;
    this.c = c;
    this.d = d;
    this.f = f;
  }
  getSyncStoreType(userData) {
    const remoteGlobalState = this.h(userData);
    return remoteGlobalState?.storage[$Urb]?.value;
  }
  async sync(userDataSyncStoreType) {
    const syncHeaders = $Qrb($jh());
    try {
      return await this.g(userDataSyncStoreType, syncHeaders);
    } catch (e) {
      if (e instanceof $Rrb) {
        switch (e.code) {
          case "PreconditionFailed":
            this.f.info(`Failed to synchronize UserDataSyncStoreType as there is a new remote version available. Synchronizing again...`);
            return this.g(userDataSyncStoreType, syncHeaders);
        }
      }
      throw e;
    }
  }
  async g(userDataSyncStoreType, syncHeaders) {
    const globalStateUserData = await this.a.readResource("globalState", null, void 0, syncHeaders);
    const remoteGlobalState = this.h(globalStateUserData) || { storage: {} };
    remoteGlobalState.storage[$Urb] = { value: userDataSyncStoreType, version: GLOBAL_STATE_DATA_VERSION };
    const machineId = await $Jq(this.c, this.d, this.b);
    const syncDataToUpdate = { version: GLOBAL_STATE_DATA_VERSION, machineId, content: $nTb(remoteGlobalState, false) };
    await this.a.writeResource("globalState", JSON.stringify(syncDataToUpdate), globalStateUserData.ref, void 0, syncHeaders);
  }
  h({ content }) {
    if (!content) {
      return null;
    }
    const syncData = JSON.parse(content);
    if ($gTb(syncData)) {
      return syncData ? JSON.parse(syncData.content) : null;
    }
    throw new Error("Invalid remote data");
  }
};
$rTb = __decorate([
  __param(1, $Dq),
  __param(2, $7i),
  __param(3, $ul),
  __param(4, $uk)
], $rTb);

// out-build/vs/platform/userDataSync/common/keybindingsMerge.js
function parseKeybindings(content) {
  return $ho(content) || [];
}
async function $Wgc(localContent, remoteContent, baseContent, formattingOptions, userDataSyncUtilService) {
  const local = parseKeybindings(localContent);
  const remote = parseKeybindings(remoteContent);
  const base = baseContent ? parseKeybindings(baseContent) : null;
  const userbindings = [...local, ...remote, ...base || []].map((keybinding) => keybinding.key);
  const normalizedKeys = await userDataSyncUtilService.resolveUserBindings(userbindings);
  const keybindingsMergeResult = computeMergeResultByKeybinding(local, remote, base, normalizedKeys);
  if (!keybindingsMergeResult.hasLocalForwarded && !keybindingsMergeResult.hasRemoteForwarded) {
    return { mergeContent: localContent, hasChanges: false, hasConflicts: false };
  }
  if (!keybindingsMergeResult.hasLocalForwarded && keybindingsMergeResult.hasRemoteForwarded) {
    return { mergeContent: remoteContent, hasChanges: true, hasConflicts: false };
  }
  if (keybindingsMergeResult.hasLocalForwarded && !keybindingsMergeResult.hasRemoteForwarded) {
    return { mergeContent: localContent, hasChanges: true, hasConflicts: false };
  }
  const localByCommand = byCommand(local);
  const remoteByCommand = byCommand(remote);
  const baseByCommand = base ? byCommand(base) : null;
  const localToRemoteByCommand = compareByCommand(localByCommand, remoteByCommand, normalizedKeys);
  const baseToLocalByCommand = baseByCommand ? compareByCommand(baseByCommand, localByCommand, normalizedKeys) : { added: [...localByCommand.keys()].reduce((r, k) => {
    r.add(k);
    return r;
  }, /* @__PURE__ */ new Set()), removed: /* @__PURE__ */ new Set(), updated: /* @__PURE__ */ new Set() };
  const baseToRemoteByCommand = baseByCommand ? compareByCommand(baseByCommand, remoteByCommand, normalizedKeys) : { added: [...remoteByCommand.keys()].reduce((r, k) => {
    r.add(k);
    return r;
  }, /* @__PURE__ */ new Set()), removed: /* @__PURE__ */ new Set(), updated: /* @__PURE__ */ new Set() };
  const commandsMergeResult = computeMergeResult(localToRemoteByCommand, baseToLocalByCommand, baseToRemoteByCommand);
  let mergeContent = localContent;
  for (const command of commandsMergeResult.removed.values()) {
    if (commandsMergeResult.conflicts.has(command)) {
      continue;
    }
    mergeContent = removeKeybindings(mergeContent, command, formattingOptions);
  }
  for (const command of commandsMergeResult.added.values()) {
    if (commandsMergeResult.conflicts.has(command)) {
      continue;
    }
    const keybindings = remoteByCommand.get(command);
    if (keybindings.some((keybinding) => keybinding.command !== `-${command}` && keybindingsMergeResult.conflicts.has(normalizedKeys[keybinding.key]))) {
      commandsMergeResult.conflicts.add(command);
      continue;
    }
    mergeContent = addKeybindings(mergeContent, keybindings, formattingOptions);
  }
  for (const command of commandsMergeResult.updated.values()) {
    if (commandsMergeResult.conflicts.has(command)) {
      continue;
    }
    const keybindings = remoteByCommand.get(command);
    if (keybindings.some((keybinding) => keybinding.command !== `-${command}` && keybindingsMergeResult.conflicts.has(normalizedKeys[keybinding.key]))) {
      commandsMergeResult.conflicts.add(command);
      continue;
    }
    mergeContent = updateKeybindings(mergeContent, command, keybindings, formattingOptions);
  }
  return { mergeContent, hasChanges: true, hasConflicts: commandsMergeResult.conflicts.size > 0 };
}
function computeMergeResult(localToRemote, baseToLocal, baseToRemote) {
  const added = /* @__PURE__ */ new Set();
  const removed = /* @__PURE__ */ new Set();
  const updated = /* @__PURE__ */ new Set();
  const conflicts = /* @__PURE__ */ new Set();
  for (const key of baseToLocal.removed.values()) {
    if (baseToRemote.updated.has(key)) {
      conflicts.add(key);
    }
  }
  for (const key of baseToRemote.removed.values()) {
    if (conflicts.has(key)) {
      continue;
    }
    if (baseToLocal.updated.has(key)) {
      conflicts.add(key);
    } else {
      removed.add(key);
    }
  }
  for (const key of baseToLocal.added.values()) {
    if (conflicts.has(key)) {
      continue;
    }
    if (baseToRemote.added.has(key)) {
      if (localToRemote.updated.has(key)) {
        conflicts.add(key);
      }
    }
  }
  for (const key of baseToRemote.added.values()) {
    if (conflicts.has(key)) {
      continue;
    }
    if (baseToLocal.added.has(key)) {
      if (localToRemote.updated.has(key)) {
        conflicts.add(key);
      }
    } else {
      added.add(key);
    }
  }
  for (const key of baseToLocal.updated.values()) {
    if (conflicts.has(key)) {
      continue;
    }
    if (baseToRemote.updated.has(key)) {
      if (localToRemote.updated.has(key)) {
        conflicts.add(key);
      }
    }
  }
  for (const key of baseToRemote.updated.values()) {
    if (conflicts.has(key)) {
      continue;
    }
    if (baseToLocal.updated.has(key)) {
      if (localToRemote.updated.has(key)) {
        conflicts.add(key);
      }
    } else {
      updated.add(key);
    }
  }
  return { added, removed, updated, conflicts };
}
function computeMergeResultByKeybinding(local, remote, base, normalizedKeys) {
  const empty = /* @__PURE__ */ new Set();
  const localByKeybinding = byKeybinding(local, normalizedKeys);
  const remoteByKeybinding = byKeybinding(remote, normalizedKeys);
  const baseByKeybinding = base ? byKeybinding(base, normalizedKeys) : null;
  const localToRemoteByKeybinding = compareByKeybinding(localByKeybinding, remoteByKeybinding);
  if (localToRemoteByKeybinding.added.size === 0 && localToRemoteByKeybinding.removed.size === 0 && localToRemoteByKeybinding.updated.size === 0) {
    return { hasLocalForwarded: false, hasRemoteForwarded: false, added: empty, removed: empty, updated: empty, conflicts: empty };
  }
  const baseToLocalByKeybinding = baseByKeybinding ? compareByKeybinding(baseByKeybinding, localByKeybinding) : { added: [...localByKeybinding.keys()].reduce((r, k) => {
    r.add(k);
    return r;
  }, /* @__PURE__ */ new Set()), removed: /* @__PURE__ */ new Set(), updated: /* @__PURE__ */ new Set() };
  if (baseToLocalByKeybinding.added.size === 0 && baseToLocalByKeybinding.removed.size === 0 && baseToLocalByKeybinding.updated.size === 0) {
    return { hasLocalForwarded: false, hasRemoteForwarded: true, added: empty, removed: empty, updated: empty, conflicts: empty };
  }
  const baseToRemoteByKeybinding = baseByKeybinding ? compareByKeybinding(baseByKeybinding, remoteByKeybinding) : { added: [...remoteByKeybinding.keys()].reduce((r, k) => {
    r.add(k);
    return r;
  }, /* @__PURE__ */ new Set()), removed: /* @__PURE__ */ new Set(), updated: /* @__PURE__ */ new Set() };
  if (baseToRemoteByKeybinding.added.size === 0 && baseToRemoteByKeybinding.removed.size === 0 && baseToRemoteByKeybinding.updated.size === 0) {
    return { hasLocalForwarded: true, hasRemoteForwarded: false, added: empty, removed: empty, updated: empty, conflicts: empty };
  }
  const { added, removed, updated, conflicts } = computeMergeResult(localToRemoteByKeybinding, baseToLocalByKeybinding, baseToRemoteByKeybinding);
  return { hasLocalForwarded: true, hasRemoteForwarded: true, added, removed, updated, conflicts };
}
function byKeybinding(keybindings, keys) {
  const map = /* @__PURE__ */ new Map();
  for (const keybinding of keybindings) {
    const key = keys[keybinding.key];
    let value = map.get(key);
    if (!value) {
      value = [];
      map.set(key, value);
    }
    value.push(keybinding);
  }
  return map;
}
function byCommand(keybindings) {
  const map = /* @__PURE__ */ new Map();
  for (const keybinding of keybindings) {
    const command = keybinding.command[0] === "-" ? keybinding.command.substring(1) : keybinding.command;
    let value = map.get(command);
    if (!value) {
      value = [];
      map.set(command, value);
    }
    value.push(keybinding);
  }
  return map;
}
function compareByKeybinding(from, to) {
  const fromKeys = [...from.keys()];
  const toKeys = [...to.keys()];
  const added = toKeys.filter((key) => !fromKeys.includes(key)).reduce((r, key) => {
    r.add(key);
    return r;
  }, /* @__PURE__ */ new Set());
  const removed = fromKeys.filter((key) => !toKeys.includes(key)).reduce((r, key) => {
    r.add(key);
    return r;
  }, /* @__PURE__ */ new Set());
  const updated = /* @__PURE__ */ new Set();
  for (const key of fromKeys) {
    if (removed.has(key)) {
      continue;
    }
    const value1 = from.get(key).map((keybinding) => ({ ...keybinding, ...{ key } }));
    const value2 = to.get(key).map((keybinding) => ({ ...keybinding, ...{ key } }));
    if (!$Hb(value1, value2, (a, b) => isSameKeybinding(a, b))) {
      updated.add(key);
    }
  }
  return { added, removed, updated };
}
function compareByCommand(from, to, normalizedKeys) {
  const fromKeys = [...from.keys()];
  const toKeys = [...to.keys()];
  const added = toKeys.filter((key) => !fromKeys.includes(key)).reduce((r, key) => {
    r.add(key);
    return r;
  }, /* @__PURE__ */ new Set());
  const removed = fromKeys.filter((key) => !toKeys.includes(key)).reduce((r, key) => {
    r.add(key);
    return r;
  }, /* @__PURE__ */ new Set());
  const updated = /* @__PURE__ */ new Set();
  for (const key of fromKeys) {
    if (removed.has(key)) {
      continue;
    }
    const value1 = from.get(key).map((keybinding) => ({ ...keybinding, ...{ key: normalizedKeys[keybinding.key] } }));
    const value2 = to.get(key).map((keybinding) => ({ ...keybinding, ...{ key: normalizedKeys[keybinding.key] } }));
    if (!areSameKeybindingsWithSameCommand(value1, value2)) {
      updated.add(key);
    }
  }
  return { added, removed, updated };
}
function areSameKeybindingsWithSameCommand(value1, value2) {
  if (!$Hb(value1.filter(({ command }) => command[0] !== "-"), value2.filter(({ command }) => command[0] !== "-"), (a, b) => isSameKeybinding(a, b))) {
    return false;
  }
  if (!$Hb(value1.filter(({ command }) => command[0] === "-"), value2.filter(({ command }) => command[0] === "-"), (a, b) => isSameKeybinding(a, b))) {
    return false;
  }
  return true;
}
function isSameKeybinding(a, b) {
  if (a.command !== b.command) {
    return false;
  }
  if (a.key !== b.key) {
    return false;
  }
  const whenA = $Xj.deserialize(a.when);
  const whenB = $Xj.deserialize(b.when);
  if (whenA && !whenB || !whenA && whenB) {
    return false;
  }
  if (whenA && whenB && !whenA.equals(whenB)) {
    return false;
  }
  if (!$Do(a.args, b.args)) {
    return false;
  }
  return true;
}
function addKeybindings(content, keybindings, formattingOptions) {
  for (const keybinding of keybindings) {
    content = edit(content, [-1], keybinding, formattingOptions);
  }
  return content;
}
function removeKeybindings(content, command, formattingOptions) {
  const keybindings = parseKeybindings(content);
  for (let index = keybindings.length - 1; index >= 0; index--) {
    if (keybindings[index].command === command || keybindings[index].command === `-${command}`) {
      content = edit(content, [index], void 0, formattingOptions);
    }
  }
  return content;
}
function updateKeybindings(content, command, keybindings, formattingOptions) {
  const allKeybindings = parseKeybindings(content);
  const location = allKeybindings.findIndex((keybinding) => keybinding.command === command || keybinding.command === `-${command}`);
  for (let index = allKeybindings.length - 1; index >= 0; index--) {
    if (allKeybindings[index].command === command || allKeybindings[index].command === `-${command}`) {
      content = edit(content, [index], void 0, formattingOptions);
    }
  }
  for (let index = keybindings.length - 1; index >= 0; index--) {
    content = edit(content, [location], keybindings[index], formattingOptions);
  }
  return content;
}

// out-build/vs/platform/userDataSync/common/keybindingsSync.js
function $Xgc(syncContent, platformSpecific, logService) {
  try {
    const parsed = JSON.parse(syncContent);
    if (!platformSpecific) {
      return $Fg(parsed.all) ? null : parsed.all;
    }
    switch (OS) {
      case 2:
        return $Fg(parsed.mac) ? null : parsed.mac;
      case 3:
        return $Fg(parsed.linux) ? null : parsed.linux;
      case 1:
        return $Fg(parsed.windows) ? null : parsed.windows;
    }
  } catch (e) {
    logService.error(e);
    return null;
  }
}
var $Ygc = class $Ygc2 extends $kTb {
  constructor(profile, collection, userDataSyncStoreService, userDataSyncLocalStoreService, logService, configurationService, userDataSyncEnablementService, fileService, environmentService, storageService, userDataSyncUtilService, telemetryService, uriIdentityService) {
    super(profile.keybindingsResource, { syncResource: "keybindings", profile }, collection, fileService, environmentService, storageService, userDataSyncStoreService, userDataSyncLocalStoreService, userDataSyncEnablementService, telemetryService, logService, userDataSyncUtilService, configurationService, uriIdentityService);
    this.pb = 2;
    this.Eb = this.h.joinPath(this.g, "keybindings.json");
    this.Fb = this.Eb.with({ scheme: $4rb, authority: "base" });
    this.Gb = this.Eb.with({ scheme: $4rb, authority: "local" });
    this.Hb = this.Eb.with({ scheme: $4rb, authority: "remote" });
    this.Ib = this.Eb.with({ scheme: $4rb, authority: "accepted" });
    this.B(Event.filter(configurationService.onDidChangeConfiguration, (e) => e.affectsConfiguration("settingsSync.keybindingsPerPlatform"))(() => this.Q()));
  }
  async qb(remoteUserData, lastSyncUserData, isRemoteDataFromCurrentMachine, userDataSyncConfiguration) {
    const remoteContent = remoteUserData.syncData ? $Xgc(remoteUserData.syncData.content, userDataSyncConfiguration.keybindingsPerPlatform ?? this.Qb(), this.O) : null;
    lastSyncUserData = lastSyncUserData === null && isRemoteDataFromCurrentMachine ? remoteUserData : lastSyncUserData;
    const lastSyncContent = lastSyncUserData ? this.Ob(lastSyncUserData) : null;
    const fileContent = await this.vb();
    const formattingOptions = await this.Cb();
    let mergedContent = null;
    let hasLocalChanged = false;
    let hasRemoteChanged = false;
    let hasConflicts = false;
    if (remoteContent) {
      let localContent2 = fileContent ? fileContent.value.toString() : "[]";
      localContent2 = localContent2 || "[]";
      if (this.Ab(localContent2, true)) {
        throw new $Rrb(localize(2459, null), "LocalInvalidContent", this.resource);
      }
      if (!lastSyncContent || lastSyncContent !== localContent2 || lastSyncContent !== remoteContent) {
        this.O.trace(`${this.D}: Merging remote keybindings with local keybindings...`);
        const result = await $Wgc(localContent2, remoteContent, lastSyncContent, formattingOptions, this.zb);
        if (result.hasChanges) {
          mergedContent = result.mergeContent;
          hasConflicts = result.hasConflicts;
          hasLocalChanged = hasConflicts || result.mergeContent !== localContent2;
          hasRemoteChanged = hasConflicts || result.mergeContent !== remoteContent;
        }
      }
    } else if (fileContent) {
      this.O.trace(`${this.D}: Remote keybindings does not exist. Synchronizing keybindings for the first time.`);
      mergedContent = fileContent.value.toString();
      hasRemoteChanged = true;
    }
    const previewResult = {
      content: hasConflicts ? lastSyncContent : mergedContent,
      localChange: hasLocalChanged ? fileContent ? 2 : 1 : 0,
      remoteChange: hasRemoteChanged ? 2 : 0,
      hasConflicts
    };
    const localContent = fileContent ? fileContent.value.toString() : null;
    return [{
      fileContent,
      baseResource: this.Fb,
      baseContent: lastSyncContent,
      localResource: this.Gb,
      localContent,
      localChange: previewResult.localChange,
      remoteResource: this.Hb,
      remoteContent,
      remoteChange: previewResult.remoteChange,
      previewResource: this.Eb,
      previewResult,
      acceptedResource: this.Ib
    }];
  }
  async ub(lastSyncUserData) {
    const lastSyncContent = this.Ob(lastSyncUserData);
    if (lastSyncContent === null) {
      return true;
    }
    const fileContent = await this.vb();
    const localContent = fileContent ? fileContent.value.toString() : "";
    const formattingOptions = await this.Cb();
    const result = await $Wgc(localContent || "[]", lastSyncContent, lastSyncContent, formattingOptions, this.zb);
    return result.hasConflicts || result.mergeContent !== lastSyncContent;
  }
  async rb(resourcePreview, token) {
    return resourcePreview.previewResult;
  }
  async sb(resourcePreview, resource, content, token) {
    if (this.h.isEqual(resource, this.Gb)) {
      return {
        content: resourcePreview.fileContent ? resourcePreview.fileContent.value.toString() : null,
        localChange: 0,
        remoteChange: 2
      };
    }
    if (this.h.isEqual(resource, this.Hb)) {
      return {
        content: resourcePreview.remoteContent,
        localChange: 2,
        remoteChange: 0
      };
    }
    if (this.h.isEqual(resource, this.Eb)) {
      if (content === void 0) {
        return {
          content: resourcePreview.previewResult.content,
          localChange: resourcePreview.previewResult.localChange,
          remoteChange: resourcePreview.previewResult.remoteChange
        };
      } else {
        return {
          content,
          localChange: 2,
          remoteChange: 2
        };
      }
    }
    throw new Error(`Invalid Resource: ${resource.toString()}`);
  }
  async tb(remoteUserData, lastSyncUserData, resourcePreviews, force) {
    const { fileContent } = resourcePreviews[0][0];
    let { content, localChange, remoteChange } = resourcePreviews[0][1];
    if (localChange === 0 && remoteChange === 0) {
      this.O.info(`${this.D}: No changes found during synchronizing keybindings.`);
    }
    if (content !== null) {
      content = content.trim();
      content = content || "[]";
      if (this.Ab(content, true)) {
        throw new $Rrb(localize(2460, null), "LocalInvalidContent", this.resource);
      }
    }
    if (localChange !== 0) {
      this.O.trace(`${this.D}: Updating local keybindings...`);
      if (fileContent) {
        await this.nb(this.Pb(fileContent.value.toString()));
      }
      await this.wb(content || "[]", fileContent, force);
      this.O.info(`${this.D}: Updated local keybindings`);
    }
    if (remoteChange !== 0) {
      this.O.trace(`${this.D}: Updating remote keybindings...`);
      const remoteContents = this.Pb(content || "[]", remoteUserData.syncData?.content);
      remoteUserData = await this.mb(remoteContents, force ? null : remoteUserData.ref);
      this.O.info(`${this.D}: Updated remote keybindings`);
    }
    try {
      await this.G.del(this.Eb);
    } catch (e) {
    }
    if (lastSyncUserData?.ref !== remoteUserData.ref) {
      this.O.trace(`${this.D}: Updating last synchronized keybindings...`);
      await this.fb(remoteUserData, { platformSpecific: this.Qb() });
      this.O.info(`${this.D}: Updated last synchronized keybindings`);
    }
  }
  async hasLocalData() {
    try {
      const localFileContent = await this.vb();
      if (localFileContent) {
        const keybindings = $ho(localFileContent.value.toString());
        if ($Yb(keybindings)) {
          return true;
        }
      }
    } catch (error) {
      if (error.fileOperationResult !== 1) {
        return true;
      }
    }
    return false;
  }
  async resolveContent(uri) {
    if (this.h.isEqual(this.Hb, uri) || this.h.isEqual(this.Fb, uri) || this.h.isEqual(this.Gb, uri) || this.h.isEqual(this.Ib, uri)) {
      return this.db(uri);
    }
    return null;
  }
  Ob(lastSyncUserData) {
    if (!lastSyncUserData.syncData) {
      return null;
    }
    if (lastSyncUserData.platformSpecific !== void 0 && lastSyncUserData.platformSpecific !== this.Qb()) {
      return null;
    }
    return $Xgc(lastSyncUserData.syncData.content, this.Qb(), this.O);
  }
  Pb(keybindingsContent, syncContent) {
    let parsed = {};
    try {
      parsed = JSON.parse(syncContent || "{}");
    } catch (e) {
      this.O.error(e);
    }
    if (this.Qb()) {
      delete parsed.all;
    } else {
      parsed.all = keybindingsContent;
    }
    switch (OS) {
      case 2:
        parsed.mac = keybindingsContent;
        break;
      case 3:
        parsed.linux = keybindingsContent;
        break;
      case 1:
        parsed.windows = keybindingsContent;
        break;
    }
    return JSON.stringify(parsed);
  }
  Qb() {
    return !!this.P.getValue($Frb);
  }
};
$Ygc = __decorate([
  __param(2, $Mrb),
  __param(3, $Nrb),
  __param(4, $2rb),
  __param(5, $tj),
  __param(6, $Wrb),
  __param(7, $ul),
  __param(8, $7i),
  __param(9, $Dq),
  __param(10, $1rb),
  __param(11, $tm),
  __param(12, $5l)
], $Ygc);
var $Zgc = class $Zgc2 extends $lTb {
  constructor(fileService, userDataProfilesService, environmentService, logService, storageService, uriIdentityService) {
    super("keybindings", userDataProfilesService, environmentService, logService, fileService, storageService, uriIdentityService);
  }
  async o(remoteUserData) {
    const keybindingsContent = remoteUserData.syncData ? this.p(remoteUserData.syncData.content) : null;
    if (!keybindingsContent) {
      this.j.info("Skipping initializing keybindings because remote keybindings does not exist.");
      return;
    }
    const isEmpty = await this.i();
    if (!isEmpty) {
      this.j.info("Skipping initializing keybindings because local keybindings exist.");
      return;
    }
    await this.k.writeFile(this.g.defaultProfile.keybindingsResource, $7e.fromString(keybindingsContent));
    await this.n(remoteUserData);
  }
  async i() {
    try {
      const fileContent = await this.k.readFile(this.g.defaultProfile.settingsResource);
      const keybindings = $ho(fileContent.value.toString());
      return !$Yb(keybindings);
    } catch (error) {
      return error.fileOperationResult === 1;
    }
  }
  p(syncContent) {
    try {
      return $Xgc(syncContent, true, this.j);
    } catch (e) {
      this.j.error(e);
      return null;
    }
  }
};
$Zgc = __decorate([
  __param(0, $ul),
  __param(1, $7l),
  __param(2, $7i),
  __param(3, $2rb),
  __param(4, $Dq),
  __param(5, $5l)
], $Zgc);

// out-build/vs/platform/userDataSync/common/settingsMerge.js
function $WRb(defaultIgnoredSettings, configurationService, settingsContent) {
  let value = [];
  if (settingsContent) {
    value = getIgnoredSettingsFromContent(settingsContent);
  } else {
    value = getIgnoredSettingsFromConfig(configurationService);
  }
  const added = [], removed = [...$Brb()];
  if (Array.isArray(value)) {
    for (const key of value) {
      if (key.startsWith("-")) {
        removed.push(key.substring(1));
      } else {
        added.push(key);
      }
    }
  }
  return $Zb([...defaultIgnoredSettings, ...added].filter((setting) => !removed.includes(setting)));
}
function getIgnoredSettingsFromConfig(configurationService) {
  let userValue = configurationService.inspect("settingsSync.ignoredSettings").userValue;
  if (userValue !== void 0) {
    return userValue;
  }
  userValue = configurationService.inspect("sync.ignoredSettings").userValue;
  if (userValue !== void 0) {
    return userValue;
  }
  return configurationService.getValue("settingsSync.ignoredSettings") || [];
}
function getIgnoredSettingsFromContent(settingsContent) {
  const parsed = $ho(settingsContent);
  return parsed ? parsed["settingsSync.ignoredSettings"] || parsed["sync.ignoredSettings"] || [] : [];
}
function $YRb(targetContent, sourceContent, ignoredSettings, formattingOptions) {
  if (ignoredSettings.length) {
    const sourceTree = parseSettings(sourceContent);
    const source = $ho(sourceContent) || {};
    const target = $ho(targetContent);
    if (!target) {
      return targetContent;
    }
    const settingsToAdd = [];
    for (const key of ignoredSettings) {
      const sourceValue = source[key];
      const targetValue = target[key];
      if (sourceValue === void 0) {
        targetContent = edit(targetContent, [key], void 0, formattingOptions);
      } else if (targetValue !== void 0) {
        targetContent = edit(targetContent, [key], sourceValue, formattingOptions);
      } else {
        settingsToAdd.push(findSettingNode(key, sourceTree));
      }
    }
    settingsToAdd.sort((a, b) => a.startOffset - b.startOffset);
    settingsToAdd.forEach((s) => targetContent = $2Rb(s.setting.key, sourceContent, targetContent, formattingOptions));
  }
  return targetContent;
}
function $ZRb(originalLocalContent, originalRemoteContent, baseContent, ignoredSettings, resolvedConflicts, formattingOptions) {
  const localContentWithoutIgnoredSettings = $YRb(originalLocalContent, originalRemoteContent, ignoredSettings, formattingOptions);
  const localForwarded = baseContent !== localContentWithoutIgnoredSettings;
  const remoteForwarded = baseContent !== originalRemoteContent;
  if (!localForwarded && !remoteForwarded) {
    return { conflictsSettings: [], localContent: null, remoteContent: null, hasConflicts: false };
  }
  if (localForwarded && !remoteForwarded) {
    return { conflictsSettings: [], localContent: null, remoteContent: localContentWithoutIgnoredSettings, hasConflicts: false };
  }
  if (remoteForwarded && !localForwarded) {
    return { conflictsSettings: [], localContent: $YRb(originalRemoteContent, originalLocalContent, ignoredSettings, formattingOptions), remoteContent: null, hasConflicts: false };
  }
  if (baseContent === null && $1Rb(originalLocalContent)) {
    const localContent2 = areSame2(originalLocalContent, originalRemoteContent, ignoredSettings) ? null : $YRb(originalRemoteContent, originalLocalContent, ignoredSettings, formattingOptions);
    return { conflictsSettings: [], localContent: localContent2, remoteContent: null, hasConflicts: false };
  }
  let localContent = originalLocalContent;
  let remoteContent = originalRemoteContent;
  const local = $ho(originalLocalContent);
  const remote = $ho(originalRemoteContent);
  const base = baseContent ? $ho(baseContent) : null;
  const ignored = ignoredSettings.reduce((set, key) => {
    set.add(key);
    return set;
  }, /* @__PURE__ */ new Set());
  const localToRemote = compare5(local, remote, ignored);
  const baseToLocal = compare5(base, local, ignored);
  const baseToRemote = compare5(base, remote, ignored);
  const conflicts = /* @__PURE__ */ new Map();
  const handledConflicts = /* @__PURE__ */ new Set();
  const handleConflict = (conflictKey) => {
    handledConflicts.add(conflictKey);
    const resolvedConflict = resolvedConflicts.filter(({ key }) => key === conflictKey)[0];
    if (resolvedConflict) {
      localContent = edit(localContent, [conflictKey], resolvedConflict.value, formattingOptions);
      remoteContent = edit(remoteContent, [conflictKey], resolvedConflict.value, formattingOptions);
    } else {
      conflicts.set(conflictKey, { key: conflictKey, localValue: local[conflictKey], remoteValue: remote[conflictKey] });
    }
  };
  for (const key of baseToLocal.removed.values()) {
    if (baseToRemote.updated.has(key)) {
      handleConflict(key);
    } else {
      remoteContent = edit(remoteContent, [key], void 0, formattingOptions);
    }
  }
  for (const key of baseToRemote.removed.values()) {
    if (handledConflicts.has(key)) {
      continue;
    }
    if (baseToLocal.updated.has(key)) {
      handleConflict(key);
    } else {
      localContent = edit(localContent, [key], void 0, formattingOptions);
    }
  }
  for (const key of baseToLocal.updated.values()) {
    if (handledConflicts.has(key)) {
      continue;
    }
    if (baseToRemote.updated.has(key)) {
      if (localToRemote.updated.has(key)) {
        handleConflict(key);
      }
    } else {
      remoteContent = edit(remoteContent, [key], local[key], formattingOptions);
    }
  }
  for (const key of baseToRemote.updated.values()) {
    if (handledConflicts.has(key)) {
      continue;
    }
    if (baseToLocal.updated.has(key)) {
      if (localToRemote.updated.has(key)) {
        handleConflict(key);
      }
    } else {
      localContent = edit(localContent, [key], remote[key], formattingOptions);
    }
  }
  for (const key of baseToLocal.added.values()) {
    if (handledConflicts.has(key)) {
      continue;
    }
    if (baseToRemote.added.has(key)) {
      if (localToRemote.updated.has(key)) {
        handleConflict(key);
      }
    } else {
      remoteContent = $2Rb(key, localContent, remoteContent, formattingOptions);
    }
  }
  for (const key of baseToRemote.added.values()) {
    if (handledConflicts.has(key)) {
      continue;
    }
    if (baseToLocal.added.has(key)) {
      if (localToRemote.updated.has(key)) {
        handleConflict(key);
      }
    } else {
      localContent = $2Rb(key, remoteContent, localContent, formattingOptions);
    }
  }
  const hasConflicts = conflicts.size > 0 || !areSame2(localContent, remoteContent, ignoredSettings);
  const hasLocalChanged = hasConflicts || !areSame2(localContent, originalLocalContent, []);
  const hasRemoteChanged = hasConflicts || !areSame2(remoteContent, originalRemoteContent, []);
  return { localContent: hasLocalChanged ? localContent : null, remoteContent: hasRemoteChanged ? remoteContent : null, conflictsSettings: [...conflicts.values()], hasConflicts };
}
function areSame2(localContent, remoteContent, ignoredSettings) {
  if (localContent === remoteContent) {
    return true;
  }
  const local = $ho(localContent);
  const remote = $ho(remoteContent);
  const ignored = ignoredSettings.reduce((set, key) => {
    set.add(key);
    return set;
  }, /* @__PURE__ */ new Set());
  const localTree = parseSettings(localContent).filter((node) => !(node.setting && ignored.has(node.setting.key)));
  const remoteTree = parseSettings(remoteContent).filter((node) => !(node.setting && ignored.has(node.setting.key)));
  if (localTree.length !== remoteTree.length) {
    return false;
  }
  for (let index = 0; index < localTree.length; index++) {
    const localNode = localTree[index];
    const remoteNode = remoteTree[index];
    if (localNode.setting && remoteNode.setting) {
      if (localNode.setting.key !== remoteNode.setting.key) {
        return false;
      }
      if (!$Do(local[localNode.setting.key], remote[localNode.setting.key])) {
        return false;
      }
    } else if (!localNode.setting && !remoteNode.setting) {
      if (localNode.value !== remoteNode.value) {
        return false;
      }
    } else {
      return false;
    }
  }
  return true;
}
function $1Rb(content) {
  if (content) {
    const nodes = parseSettings(content);
    return nodes.length === 0;
  }
  return true;
}
function compare5(from, to, ignored) {
  const fromKeys = from ? Object.keys(from).filter((key) => !ignored.has(key)) : [];
  const toKeys = Object.keys(to).filter((key) => !ignored.has(key));
  const added = toKeys.filter((key) => !fromKeys.includes(key)).reduce((r, key) => {
    r.add(key);
    return r;
  }, /* @__PURE__ */ new Set());
  const removed = fromKeys.filter((key) => !toKeys.includes(key)).reduce((r, key) => {
    r.add(key);
    return r;
  }, /* @__PURE__ */ new Set());
  const updated = /* @__PURE__ */ new Set();
  if (from) {
    for (const key of fromKeys) {
      if (removed.has(key)) {
        continue;
      }
      const value1 = from[key];
      const value2 = to[key];
      if (!$Do(value1, value2)) {
        updated.add(key);
      }
    }
  }
  return { added, removed, updated };
}
function $2Rb(key, sourceContent, targetContent, formattingOptions) {
  const source = $ho(sourceContent);
  const sourceTree = parseSettings(sourceContent);
  const targetTree = parseSettings(targetContent);
  const insertLocation = getInsertLocation(key, sourceTree, targetTree);
  return insertAtLocation(targetContent, key, source[key], insertLocation, targetTree, formattingOptions);
}
function getInsertLocation(key, sourceTree, targetTree) {
  const sourceNodeIndex = sourceTree.findIndex((node) => node.setting?.key === key);
  const sourcePreviousNode = sourceTree[sourceNodeIndex - 1];
  if (sourcePreviousNode) {
    if (sourcePreviousNode.setting) {
      const targetPreviousSetting = findSettingNode(sourcePreviousNode.setting.key, targetTree);
      if (targetPreviousSetting) {
        return { index: targetTree.indexOf(targetPreviousSetting), insertAfter: true };
      }
    } else {
      const sourcePreviousSettingNode = findPreviousSettingNode(sourceNodeIndex, sourceTree);
      if (sourcePreviousSettingNode) {
        const targetPreviousSetting = findSettingNode(sourcePreviousSettingNode.setting.key, targetTree);
        if (targetPreviousSetting) {
          const targetNextSetting = findNextSettingNode(targetTree.indexOf(targetPreviousSetting), targetTree);
          const sourceCommentNodes = findNodesBetween(sourceTree, sourcePreviousSettingNode, sourceTree[sourceNodeIndex]);
          if (targetNextSetting) {
            const targetCommentNodes = findNodesBetween(targetTree, targetPreviousSetting, targetNextSetting);
            const targetCommentNode = findLastMatchingTargetCommentNode(sourceCommentNodes, targetCommentNodes);
            if (targetCommentNode) {
              return { index: targetTree.indexOf(targetCommentNode), insertAfter: true };
            } else {
              return { index: targetTree.indexOf(targetNextSetting), insertAfter: false };
            }
          } else {
            const targetCommentNodes = findNodesBetween(targetTree, targetPreviousSetting, targetTree[targetTree.length - 1]);
            const targetCommentNode = findLastMatchingTargetCommentNode(sourceCommentNodes, targetCommentNodes);
            if (targetCommentNode) {
              return { index: targetTree.indexOf(targetCommentNode), insertAfter: true };
            } else {
              return { index: targetTree.length - 1, insertAfter: true };
            }
          }
        }
      }
    }
    const sourceNextNode = sourceTree[sourceNodeIndex + 1];
    if (sourceNextNode) {
      if (sourceNextNode.setting) {
        const targetNextSetting = findSettingNode(sourceNextNode.setting.key, targetTree);
        if (targetNextSetting) {
          return { index: targetTree.indexOf(targetNextSetting), insertAfter: false };
        }
      } else {
        const sourceNextSettingNode = findNextSettingNode(sourceNodeIndex, sourceTree);
        if (sourceNextSettingNode) {
          const targetNextSetting = findSettingNode(sourceNextSettingNode.setting.key, targetTree);
          if (targetNextSetting) {
            const targetPreviousSetting = findPreviousSettingNode(targetTree.indexOf(targetNextSetting), targetTree);
            const sourceCommentNodes = findNodesBetween(sourceTree, sourceTree[sourceNodeIndex], sourceNextSettingNode);
            if (targetPreviousSetting) {
              const targetCommentNodes = findNodesBetween(targetTree, targetPreviousSetting, targetNextSetting);
              const targetCommentNode = findLastMatchingTargetCommentNode(sourceCommentNodes.reverse(), targetCommentNodes.reverse());
              if (targetCommentNode) {
                return { index: targetTree.indexOf(targetCommentNode), insertAfter: false };
              } else {
                return { index: targetTree.indexOf(targetPreviousSetting), insertAfter: true };
              }
            } else {
              const targetCommentNodes = findNodesBetween(targetTree, targetTree[0], targetNextSetting);
              const targetCommentNode = findLastMatchingTargetCommentNode(sourceCommentNodes.reverse(), targetCommentNodes.reverse());
              if (targetCommentNode) {
                return { index: targetTree.indexOf(targetCommentNode), insertAfter: false };
              } else {
                return { index: 0, insertAfter: false };
              }
            }
          }
        }
      }
    }
  }
  return { index: targetTree.length - 1, insertAfter: true };
}
function insertAtLocation(content, key, value, location, tree, formattingOptions) {
  let edits;
  if (location.index === -1) {
    edits = $vo(content, [key], value, formattingOptions);
  } else {
    edits = getEditToInsertAtLocation(content, key, value, location, tree, formattingOptions).map((edit2) => $wo(content, edit2, formattingOptions)[0]);
  }
  return $yo(content, edits);
}
function getEditToInsertAtLocation(content, key, value, location, tree, formattingOptions) {
  const newProperty = `${JSON.stringify(key)}: ${JSON.stringify(value)}`;
  const eol = $so(formattingOptions, content);
  const node = tree[location.index];
  if (location.insertAfter) {
    const edits = [];
    if (node.setting) {
      edits.push({ offset: node.endOffset, length: 0, content: "," + newProperty });
    } else {
      const nextSettingNode = findNextSettingNode(location.index, tree);
      const previousSettingNode = findPreviousSettingNode(location.index, tree);
      const previousSettingCommaOffset = previousSettingNode?.setting?.commaOffset;
      if (previousSettingNode && previousSettingCommaOffset === void 0) {
        edits.push({ offset: previousSettingNode.endOffset, length: 0, content: "," });
      }
      const isPreviouisSettingIncludesComment = previousSettingCommaOffset !== void 0 && previousSettingCommaOffset > node.endOffset;
      edits.push({
        offset: isPreviouisSettingIncludesComment ? previousSettingCommaOffset + 1 : node.endOffset,
        length: 0,
        content: nextSettingNode ? eol + newProperty + "," : eol + newProperty
      });
    }
    return edits;
  } else {
    if (node.setting) {
      return [{ offset: node.startOffset, length: 0, content: newProperty + "," }];
    }
    const content2 = (tree[location.index - 1] && !tree[location.index - 1].setting ? eol : "") + newProperty + (findNextSettingNode(location.index, tree) ? "," : "") + eol;
    return [{ offset: node.startOffset, length: 0, content: content2 }];
  }
}
function findSettingNode(key, tree) {
  return tree.filter((node) => node.setting?.key === key)[0];
}
function findPreviousSettingNode(index, tree) {
  for (let i = index - 1; i >= 0; i--) {
    if (tree[i].setting) {
      return tree[i];
    }
  }
  return void 0;
}
function findNextSettingNode(index, tree) {
  for (let i = index + 1; i < tree.length; i++) {
    if (tree[i].setting) {
      return tree[i];
    }
  }
  return void 0;
}
function findNodesBetween(nodes, from, till) {
  const fromIndex = nodes.indexOf(from);
  const tillIndex = nodes.indexOf(till);
  return nodes.filter((node, index) => fromIndex < index && index < tillIndex);
}
function findLastMatchingTargetCommentNode(sourceComments, targetComments) {
  if (sourceComments.length && targetComments.length) {
    let index = 0;
    for (; index < targetComments.length && index < sourceComments.length; index++) {
      if (sourceComments[index].value !== targetComments[index].value) {
        return targetComments[index - 1];
      }
    }
    return targetComments[index - 1];
  }
  return void 0;
}
function parseSettings(content) {
  const nodes = [];
  let hierarchyLevel = -1;
  let startOffset;
  let key;
  const visitor = {
    onObjectBegin: (offset) => {
      hierarchyLevel++;
    },
    onObjectProperty: (name, offset, length) => {
      if (hierarchyLevel === 0) {
        startOffset = offset;
        key = name;
      }
    },
    onObjectEnd: (offset, length) => {
      hierarchyLevel--;
      if (hierarchyLevel === 0) {
        nodes.push({
          startOffset,
          endOffset: offset + length,
          value: content.substring(startOffset, offset + length),
          setting: {
            key,
            commaOffset: void 0
          }
        });
      }
    },
    onArrayBegin: (offset, length) => {
      hierarchyLevel++;
    },
    onArrayEnd: (offset, length) => {
      hierarchyLevel--;
      if (hierarchyLevel === 0) {
        nodes.push({
          startOffset,
          endOffset: offset + length,
          value: content.substring(startOffset, offset + length),
          setting: {
            key,
            commaOffset: void 0
          }
        });
      }
    },
    onLiteralValue: (value, offset, length) => {
      if (hierarchyLevel === 0) {
        nodes.push({
          startOffset,
          endOffset: offset + length,
          value: content.substring(startOffset, offset + length),
          setting: {
            key,
            commaOffset: void 0
          }
        });
      }
    },
    onSeparator: (sep2, offset, length) => {
      if (hierarchyLevel === 0) {
        if (sep2 === ",") {
          let index = nodes.length - 1;
          for (; index >= 0; index--) {
            if (nodes[index].setting) {
              break;
            }
          }
          const node = nodes[index];
          if (node) {
            nodes.splice(index, 1, {
              startOffset: node.startOffset,
              endOffset: node.endOffset,
              value: node.value,
              setting: {
                key: node.setting.key,
                commaOffset: offset
              }
            });
          }
        }
      }
    },
    onComment: (offset, length) => {
      if (hierarchyLevel === 0) {
        nodes.push({
          startOffset: offset,
          endOffset: offset + length,
          value: content.substring(offset, offset + length)
        });
      }
    }
  };
  $oo(content, visitor);
  return nodes;
}

// out-build/vs/platform/userDataSync/common/settingsSync.js
function isSettingsSyncContent(thing) {
  return thing && (thing.settings && typeof thing.settings === "string") && Object.keys(thing).length === 1;
}
function $1gc(syncContent) {
  const parsed = JSON.parse(syncContent);
  return isSettingsSyncContent(parsed) ? parsed : (
    /* migrate */
    { settings: syncContent }
  );
}
var $2gc = class $2gc2 extends $kTb {
  constructor(Eb, collection, fileService, environmentService, storageService, userDataSyncStoreService, userDataSyncLocalStoreService, logService, userDataSyncUtilService, configurationService, userDataSyncEnablementService, telemetryService, Fb, uriIdentityService) {
    super(Eb.settingsResource, { syncResource: "settings", profile: Eb }, collection, fileService, environmentService, storageService, userDataSyncStoreService, userDataSyncLocalStoreService, userDataSyncEnablementService, telemetryService, logService, userDataSyncUtilService, configurationService, uriIdentityService);
    this.Eb = Eb;
    this.Fb = Fb;
    this.pb = 2;
    this.previewResource = this.h.joinPath(this.g, "settings.json");
    this.baseResource = this.previewResource.with({ scheme: $4rb, authority: "base" });
    this.localResource = this.previewResource.with({ scheme: $4rb, authority: "local" });
    this.remoteResource = this.previewResource.with({ scheme: $4rb, authority: "remote" });
    this.acceptedResource = this.previewResource.with({ scheme: $4rb, authority: "accepted" });
    this.Pb = void 0;
    this.Qb = void 0;
    this.Rb = void 0;
  }
  async getRemoteUserDataSyncConfiguration(manifest) {
    const lastSyncUserData = await this.getLastSyncUserData();
    const remoteUserData = await this.X(manifest, lastSyncUserData);
    const remoteSettingsSyncContent = this.Mb(remoteUserData);
    const parser = new $$o($Erb, this.O);
    if (remoteSettingsSyncContent?.settings) {
      parser.parse(remoteSettingsSyncContent.settings);
    }
    return parser.configurationModel.getValue($Erb) || {};
  }
  async qb(remoteUserData, lastSyncUserData, isRemoteDataFromCurrentMachine) {
    const fileContent = await this.vb();
    const formattingOptions = await this.Cb();
    const remoteSettingsSyncContent = this.Mb(remoteUserData);
    lastSyncUserData = lastSyncUserData === null && isRemoteDataFromCurrentMachine ? remoteUserData : lastSyncUserData;
    const lastSettingsSyncContent = lastSyncUserData ? this.Mb(lastSyncUserData) : null;
    const ignoredSettings = await this.Sb();
    let mergedContent = null;
    let hasLocalChanged = false;
    let hasRemoteChanged = false;
    let hasConflicts = false;
    if (remoteSettingsSyncContent) {
      let localContent2 = fileContent ? fileContent.value.toString().trim() : "{}";
      localContent2 = localContent2 || "{}";
      this.Vb(localContent2);
      this.O.trace(`${this.D}: Merging remote settings with local settings...`);
      const result = $ZRb(localContent2, remoteSettingsSyncContent.settings, lastSettingsSyncContent ? lastSettingsSyncContent.settings : null, ignoredSettings, [], formattingOptions);
      mergedContent = result.localContent || result.remoteContent;
      hasLocalChanged = result.localContent !== null;
      hasRemoteChanged = result.remoteContent !== null;
      hasConflicts = result.hasConflicts;
    } else if (fileContent) {
      this.O.trace(`${this.D}: Remote settings does not exist. Synchronizing settings for the first time.`);
      mergedContent = fileContent.value.toString().trim() || "{}";
      this.Vb(mergedContent);
      hasRemoteChanged = true;
    }
    const localContent = fileContent ? fileContent.value.toString() : null;
    const baseContent = lastSettingsSyncContent?.settings ?? null;
    const previewResult = {
      content: hasConflicts ? baseContent : mergedContent,
      localChange: hasLocalChanged ? 2 : 0,
      remoteChange: hasRemoteChanged ? 2 : 0,
      hasConflicts
    };
    return [{
      fileContent,
      baseResource: this.baseResource,
      baseContent,
      localResource: this.localResource,
      localContent,
      localChange: previewResult.localChange,
      remoteResource: this.remoteResource,
      remoteContent: remoteSettingsSyncContent ? remoteSettingsSyncContent.settings : null,
      remoteChange: previewResult.remoteChange,
      previewResource: this.previewResource,
      previewResult,
      acceptedResource: this.acceptedResource
    }];
  }
  async ub(lastSyncUserData) {
    const lastSettingsSyncContent = this.Mb(lastSyncUserData);
    if (lastSettingsSyncContent === null) {
      return true;
    }
    const fileContent = await this.vb();
    const localContent = fileContent ? fileContent.value.toString().trim() : "";
    const ignoredSettings = await this.Sb();
    const formattingOptions = await this.Cb();
    const result = $ZRb(localContent || "{}", lastSettingsSyncContent.settings, lastSettingsSyncContent.settings, ignoredSettings, [], formattingOptions);
    return result.remoteContent !== null;
  }
  async rb(resourcePreview, token) {
    const formatUtils = await this.Cb();
    const ignoredSettings = await this.Sb();
    return {
      ...resourcePreview.previewResult,
      // remove ignored settings from the preview content
      content: resourcePreview.previewResult.content ? $YRb(resourcePreview.previewResult.content, "{}", ignoredSettings, formatUtils) : null
    };
  }
  async sb(resourcePreview, resource, content, token) {
    const formattingOptions = await this.Cb();
    const ignoredSettings = await this.Sb();
    if (this.h.isEqual(resource, this.localResource)) {
      return {
        /* Remove ignored settings */
        content: resourcePreview.fileContent ? $YRb(resourcePreview.fileContent.value.toString(), "{}", ignoredSettings, formattingOptions) : null,
        localChange: 0,
        remoteChange: 2
      };
    }
    if (this.h.isEqual(resource, this.remoteResource)) {
      return {
        /* Update ignored settings from local file content */
        content: resourcePreview.remoteContent !== null ? $YRb(resourcePreview.remoteContent, resourcePreview.fileContent ? resourcePreview.fileContent.value.toString() : "{}", ignoredSettings, formattingOptions) : null,
        localChange: 2,
        remoteChange: 0
      };
    }
    if (this.h.isEqual(resource, this.previewResource)) {
      if (content === void 0) {
        return {
          content: resourcePreview.previewResult.content,
          localChange: resourcePreview.previewResult.localChange,
          remoteChange: resourcePreview.previewResult.remoteChange
        };
      } else {
        return {
          /* Add ignored settings from local file content */
          content: content !== null ? $YRb(content, resourcePreview.fileContent ? resourcePreview.fileContent.value.toString() : "{}", ignoredSettings, formattingOptions) : null,
          localChange: 2,
          remoteChange: 2
        };
      }
    }
    throw new Error(`Invalid Resource: ${resource.toString()}`);
  }
  async tb(remoteUserData, lastSyncUserData, resourcePreviews, force) {
    const { fileContent } = resourcePreviews[0][0];
    let { content, localChange, remoteChange } = resourcePreviews[0][1];
    if (localChange === 0 && remoteChange === 0) {
      this.O.info(`${this.D}: No changes found during synchronizing settings.`);
    }
    content = content ? content.trim() : "{}";
    content = content || "{}";
    this.Vb(content);
    if (localChange !== 0) {
      this.O.trace(`${this.D}: Updating local settings...`);
      if (fileContent) {
        await this.nb(JSON.stringify(this.Ob(fileContent.value.toString())));
      }
      await this.wb(content, fileContent, force);
      await this.P.reloadConfiguration(
        3
        /* ConfigurationTarget.USER_LOCAL */
      );
      this.O.info(`${this.D}: Updated local settings`);
    }
    if (remoteChange !== 0) {
      const formatUtils = await this.Cb();
      const remoteSettingsSyncContent = this.Mb(remoteUserData);
      const ignoredSettings = await this.Sb(content);
      content = $YRb(content, remoteSettingsSyncContent ? remoteSettingsSyncContent.settings : "{}", ignoredSettings, formatUtils);
      this.O.trace(`${this.D}: Updating remote settings...`);
      remoteUserData = await this.mb(JSON.stringify(this.Ob(content)), force ? null : remoteUserData.ref);
      this.O.info(`${this.D}: Updated remote settings`);
    }
    try {
      await this.G.del(this.previewResource);
    } catch (e) {
    }
    if (lastSyncUserData?.ref !== remoteUserData.ref) {
      this.O.trace(`${this.D}: Updating last synchronized settings...`);
      await this.fb(remoteUserData);
      this.O.info(`${this.D}: Updated last synchronized settings`);
    }
  }
  async hasLocalData() {
    try {
      const localFileContent = await this.vb();
      if (localFileContent) {
        return !$1Rb(localFileContent.value.toString());
      }
    } catch (error) {
      if (error.fileOperationResult !== 1) {
        return true;
      }
    }
    return false;
  }
  async resolveContent(uri) {
    if (this.h.isEqual(this.remoteResource, uri) || this.h.isEqual(this.localResource, uri) || this.h.isEqual(this.acceptedResource, uri) || this.h.isEqual(this.baseResource, uri)) {
      return this.db(uri);
    }
    return null;
  }
  async db(resource) {
    let content = await super.db(resource);
    if (content) {
      const formatUtils = await this.Cb();
      const ignoredSettings = await this.Sb();
      content = $YRb(content, "{}", ignoredSettings, formatUtils);
    }
    return content;
  }
  Mb(remoteUserData) {
    return remoteUserData.syncData ? this.Nb(remoteUserData.syncData.content) : null;
  }
  Nb(syncContent) {
    try {
      return $1gc(syncContent);
    } catch (e) {
      this.O.error(e);
    }
    return null;
  }
  Ob(settings) {
    return { settings };
  }
  async Sb(content) {
    if (!this.Pb) {
      this.Pb = this.zb.resolveDefaultCoreIgnoredSettings();
    }
    if (!this.Qb) {
      this.Qb = this.Tb();
    }
    if (!this.Rb) {
      this.Rb = this.Ub();
      const disposable = this.B(Event.any(Event.filter(this.Fb.onDidInstallExtensions, (e) => e.some(({ local }) => !!local)), Event.filter(this.Fb.onDidUninstallExtension, (e) => !e.error))(() => {
        disposable.dispose();
        this.Rb = void 0;
      }));
    }
    const defaultIgnoredSettings = (await Promise.all([this.Pb, this.Qb, this.Rb])).flat();
    return $WRb(defaultIgnoredSettings, this.P, content);
  }
  async Tb() {
    const systemExtensions = await this.Fb.getInstalled(
      0
      /* ExtensionType.System */
    );
    return $Zb(systemExtensions.map((e) => $Drb(e.manifest)).flat());
  }
  async Ub() {
    const userExtensions = await this.Fb.getInstalled(1, this.Eb.extensionsResource);
    return $Zb(userExtensions.map((e) => $Drb(e.manifest)).flat());
  }
  Vb(content) {
    if (this.Ab(content, false)) {
      throw new $Rrb(localize(2461, null), "LocalInvalidContent", this.resource);
    }
  }
};
$2gc = __decorate([
  __param(2, $ul),
  __param(3, $7i),
  __param(4, $Dq),
  __param(5, $Mrb),
  __param(6, $Nrb),
  __param(7, $2rb),
  __param(8, $1rb),
  __param(9, $tj),
  __param(10, $Wrb),
  __param(11, $tm),
  __param(12, $Jp),
  __param(13, $5l)
], $2gc);
var $3gc = class $3gc2 extends $lTb {
  constructor(fileService, userDataProfilesService, environmentService, logService, storageService, uriIdentityService) {
    super("settings", userDataProfilesService, environmentService, logService, fileService, storageService, uriIdentityService);
  }
  async o(remoteUserData) {
    const settingsSyncContent = remoteUserData.syncData ? this.p(remoteUserData.syncData.content) : null;
    if (!settingsSyncContent) {
      this.j.info("Skipping initializing settings because remote settings does not exist.");
      return;
    }
    const isEmpty = await this.i();
    if (!isEmpty) {
      this.j.info("Skipping initializing settings because local settings exist.");
      return;
    }
    await this.k.writeFile(this.g.defaultProfile.settingsResource, $7e.fromString(settingsSyncContent.settings));
    await this.n(remoteUserData);
  }
  async i() {
    try {
      const fileContent = await this.k.readFile(this.g.defaultProfile.settingsResource);
      return $1Rb(fileContent.value.toString().trim());
    } catch (error) {
      return error.fileOperationResult === 1;
    }
  }
  p(syncContent) {
    try {
      return $1gc(syncContent);
    } catch (e) {
      this.j.error(e);
    }
    return null;
  }
};
$3gc = __decorate([
  __param(0, $ul),
  __param(1, $7l),
  __param(2, $7i),
  __param(3, $2rb),
  __param(4, $Dq),
  __param(5, $5l)
], $3gc);

// out-build/vs/platform/userDataSync/common/snippetsMerge.js
function $4gc(local, remote, base) {
  const localAdded = {};
  const localUpdated = {};
  const localRemoved = /* @__PURE__ */ new Set();
  if (!remote) {
    return {
      local: { added: localAdded, updated: localUpdated, removed: [...localRemoved.values()] },
      remote: { added: local, updated: {}, removed: [] },
      conflicts: []
    };
  }
  const localToRemote = compare6(local, remote);
  if (localToRemote.added.size === 0 && localToRemote.removed.size === 0 && localToRemote.updated.size === 0) {
    return {
      local: { added: localAdded, updated: localUpdated, removed: [...localRemoved.values()] },
      remote: { added: {}, updated: {}, removed: [] },
      conflicts: []
    };
  }
  const baseToLocal = compare6(base, local);
  const baseToRemote = compare6(base, remote);
  const remoteAdded = {};
  const remoteUpdated = {};
  const remoteRemoved = /* @__PURE__ */ new Set();
  const conflicts = /* @__PURE__ */ new Set();
  for (const key of baseToLocal.removed.values()) {
    if (baseToRemote.updated.has(key)) {
      localAdded[key] = remote[key];
    } else {
      remoteRemoved.add(key);
    }
  }
  for (const key of baseToRemote.removed.values()) {
    if (conflicts.has(key)) {
      continue;
    }
    if (baseToLocal.updated.has(key)) {
      conflicts.add(key);
    } else {
      localRemoved.add(key);
    }
  }
  for (const key of baseToLocal.updated.values()) {
    if (conflicts.has(key)) {
      continue;
    }
    if (baseToRemote.updated.has(key)) {
      if (localToRemote.updated.has(key)) {
        conflicts.add(key);
      }
    } else {
      remoteUpdated[key] = local[key];
    }
  }
  for (const key of baseToRemote.updated.values()) {
    if (conflicts.has(key)) {
      continue;
    }
    if (baseToLocal.updated.has(key)) {
      if (localToRemote.updated.has(key)) {
        conflicts.add(key);
      }
    } else if (local[key] !== void 0) {
      localUpdated[key] = remote[key];
    }
  }
  for (const key of baseToLocal.added.values()) {
    if (conflicts.has(key)) {
      continue;
    }
    if (baseToRemote.added.has(key)) {
      if (localToRemote.updated.has(key)) {
        conflicts.add(key);
      }
    } else {
      remoteAdded[key] = local[key];
    }
  }
  for (const key of baseToRemote.added.values()) {
    if (conflicts.has(key)) {
      continue;
    }
    if (baseToLocal.added.has(key)) {
      if (localToRemote.updated.has(key)) {
        conflicts.add(key);
      }
    } else {
      localAdded[key] = remote[key];
    }
  }
  return {
    local: { added: localAdded, removed: [...localRemoved.values()], updated: localUpdated },
    remote: { added: remoteAdded, removed: [...remoteRemoved.values()], updated: remoteUpdated },
    conflicts: [...conflicts.values()]
  };
}
function compare6(from, to) {
  const fromKeys = from ? Object.keys(from) : [];
  const toKeys = to ? Object.keys(to) : [];
  const added = toKeys.filter((key) => !fromKeys.includes(key)).reduce((r, key) => {
    r.add(key);
    return r;
  }, /* @__PURE__ */ new Set());
  const removed = fromKeys.filter((key) => !toKeys.includes(key)).reduce((r, key) => {
    r.add(key);
    return r;
  }, /* @__PURE__ */ new Set());
  const updated = /* @__PURE__ */ new Set();
  for (const key of fromKeys) {
    if (removed.has(key)) {
      continue;
    }
    const fromSnippet = from[key];
    const toSnippet = to[key];
    if (fromSnippet !== toSnippet) {
      updated.add(key);
    }
  }
  return { added, removed, updated };
}
function $5gc(a, b) {
  const { added, removed, updated } = compare6(a, b);
  return added.size === 0 && removed.size === 0 && updated.size === 0;
}

// out-build/vs/platform/userDataSync/common/snippetsSync.js
function $6gc(syncData) {
  return JSON.parse(syncData.content);
}
var $7gc = class $7gc2 extends $iTb {
  constructor(profile, collection, environmentService, fileService, storageService, userDataSyncStoreService, userDataSyncLocalStoreService, logService, configurationService, userDataSyncEnablementService, telemetryService, uriIdentityService) {
    super({ syncResource: "snippets", profile }, collection, fileService, environmentService, storageService, userDataSyncStoreService, userDataSyncLocalStoreService, userDataSyncEnablementService, telemetryService, logService, configurationService, uriIdentityService);
    this.pb = 1;
    this.vb = profile.snippetsHome;
    this.B(this.G.watch(environmentService.userRoamingDataHome));
    this.B(this.G.watch(this.vb));
    this.B(Event.filter(this.G.onDidFilesChange, (e) => e.affects(this.vb))(() => this.Q()));
  }
  async qb(remoteUserData, lastSyncUserData, isRemoteDataFromCurrentMachine) {
    const local = await this.Hb();
    const localSnippets = this.Gb(local);
    const remoteSnippets = remoteUserData.syncData ? this.Fb(remoteUserData.syncData) : null;
    lastSyncUserData = lastSyncUserData === null && isRemoteDataFromCurrentMachine ? remoteUserData : lastSyncUserData;
    const lastSyncSnippets = lastSyncUserData && lastSyncUserData.syncData ? this.Fb(lastSyncUserData.syncData) : null;
    if (remoteSnippets) {
      this.O.trace(`${this.D}: Merging remote snippets with local snippets...`);
    } else {
      this.O.trace(`${this.D}: Remote snippets does not exist. Synchronizing snippets for the first time.`);
    }
    const mergeResult = $4gc(localSnippets, remoteSnippets, lastSyncSnippets);
    return this.Bb(mergeResult, local, remoteSnippets || {}, lastSyncSnippets || {});
  }
  async ub(lastSyncUserData) {
    const lastSyncSnippets = lastSyncUserData.syncData ? this.Fb(lastSyncUserData.syncData) : null;
    if (lastSyncSnippets === null) {
      return true;
    }
    const local = await this.Hb();
    const localSnippets = this.Gb(local);
    const mergeResult = $4gc(localSnippets, lastSyncSnippets, lastSyncSnippets);
    return Object.keys(mergeResult.remote.added).length > 0 || Object.keys(mergeResult.remote.updated).length > 0 || mergeResult.remote.removed.length > 0 || mergeResult.conflicts.length > 0;
  }
  async rb(resourcePreview, token) {
    return resourcePreview.previewResult;
  }
  async sb(resourcePreview, resource, content, token) {
    if (this.h.isEqualOrParent(resource, this.g.with({ scheme: $4rb, authority: "local" }))) {
      return {
        content: resourcePreview.fileContent ? resourcePreview.fileContent.value.toString() : null,
        localChange: 0,
        remoteChange: resourcePreview.fileContent ? resourcePreview.remoteContent !== null ? 2 : 1 : 3
        /* Change.Deleted */
      };
    }
    if (this.h.isEqualOrParent(resource, this.g.with({ scheme: $4rb, authority: "remote" }))) {
      return {
        content: resourcePreview.remoteContent,
        localChange: resourcePreview.remoteContent !== null ? resourcePreview.fileContent ? 2 : 1 : 3,
        remoteChange: 0
      };
    }
    if (this.h.isEqualOrParent(resource, this.g)) {
      if (content === void 0) {
        return {
          content: resourcePreview.previewResult.content,
          localChange: resourcePreview.previewResult.localChange,
          remoteChange: resourcePreview.previewResult.remoteChange
        };
      } else {
        return {
          content,
          localChange: content === null ? resourcePreview.fileContent !== null ? 3 : 0 : 2,
          remoteChange: content === null ? resourcePreview.remoteContent !== null ? 3 : 0 : 2
          /* Change.Modified */
        };
      }
    }
    throw new Error(`Invalid Resource: ${resource.toString()}`);
  }
  async tb(remoteUserData, lastSyncUserData, resourcePreviews, force) {
    const accptedResourcePreviews = resourcePreviews.map(([resourcePreview, acceptResult]) => ({ ...resourcePreview, acceptResult }));
    if (accptedResourcePreviews.every(
      ({ localChange, remoteChange }) => localChange === 0 && remoteChange === 0
      /* Change.None */
    )) {
      this.O.info(`${this.D}: No changes found during synchronizing snippets.`);
    }
    if (accptedResourcePreviews.some(
      ({ localChange }) => localChange !== 0
      /* Change.None */
    )) {
      await this.Cb(accptedResourcePreviews);
      await this.Db(accptedResourcePreviews, force);
    }
    if (accptedResourcePreviews.some(
      ({ remoteChange }) => remoteChange !== 0
      /* Change.None */
    )) {
      remoteUserData = await this.Eb(accptedResourcePreviews, remoteUserData, force);
    }
    if (lastSyncUserData?.ref !== remoteUserData.ref) {
      this.O.trace(`${this.D}: Updating last synchronized snippets...`);
      await this.fb(remoteUserData);
      this.O.info(`${this.D}: Updated last synchronized snippets`);
    }
    for (const { previewResource } of accptedResourcePreviews) {
      try {
        await this.G.del(previewResource);
      } catch (e) {
      }
    }
  }
  Bb(snippetsMergeResult, localFileContent, remoteSnippets, baseSnippets) {
    const resourcePreviews = /* @__PURE__ */ new Map();
    for (const key of Object.keys(snippetsMergeResult.local.added)) {
      const previewResult = {
        content: snippetsMergeResult.local.added[key],
        hasConflicts: false,
        localChange: 1,
        remoteChange: 0
      };
      resourcePreviews.set(key, {
        baseResource: this.h.joinPath(this.g, key).with({ scheme: $4rb, authority: "base" }),
        baseContent: null,
        fileContent: null,
        localResource: this.h.joinPath(this.g, key).with({ scheme: $4rb, authority: "local" }),
        localContent: null,
        remoteResource: this.h.joinPath(this.g, key).with({ scheme: $4rb, authority: "remote" }),
        remoteContent: remoteSnippets[key],
        previewResource: this.h.joinPath(this.g, key),
        previewResult,
        localChange: previewResult.localChange,
        remoteChange: previewResult.remoteChange,
        acceptedResource: this.h.joinPath(this.g, key).with({ scheme: $4rb, authority: "accepted" })
      });
    }
    for (const key of Object.keys(snippetsMergeResult.local.updated)) {
      const previewResult = {
        content: snippetsMergeResult.local.updated[key],
        hasConflicts: false,
        localChange: 2,
        remoteChange: 0
      };
      const localContent = localFileContent[key] ? localFileContent[key].value.toString() : null;
      resourcePreviews.set(key, {
        baseResource: this.h.joinPath(this.g, key).with({ scheme: $4rb, authority: "base" }),
        baseContent: baseSnippets[key] ?? null,
        localResource: this.h.joinPath(this.g, key).with({ scheme: $4rb, authority: "local" }),
        fileContent: localFileContent[key],
        localContent,
        remoteResource: this.h.joinPath(this.g, key).with({ scheme: $4rb, authority: "remote" }),
        remoteContent: remoteSnippets[key],
        previewResource: this.h.joinPath(this.g, key),
        previewResult,
        localChange: previewResult.localChange,
        remoteChange: previewResult.remoteChange,
        acceptedResource: this.h.joinPath(this.g, key).with({ scheme: $4rb, authority: "accepted" })
      });
    }
    for (const key of snippetsMergeResult.local.removed) {
      const previewResult = {
        content: null,
        hasConflicts: false,
        localChange: 3,
        remoteChange: 0
      };
      const localContent = localFileContent[key] ? localFileContent[key].value.toString() : null;
      resourcePreviews.set(key, {
        baseResource: this.h.joinPath(this.g, key).with({ scheme: $4rb, authority: "base" }),
        baseContent: baseSnippets[key] ?? null,
        localResource: this.h.joinPath(this.g, key).with({ scheme: $4rb, authority: "local" }),
        fileContent: localFileContent[key],
        localContent,
        remoteResource: this.h.joinPath(this.g, key).with({ scheme: $4rb, authority: "remote" }),
        remoteContent: null,
        previewResource: this.h.joinPath(this.g, key),
        previewResult,
        localChange: previewResult.localChange,
        remoteChange: previewResult.remoteChange,
        acceptedResource: this.h.joinPath(this.g, key).with({ scheme: $4rb, authority: "accepted" })
      });
    }
    for (const key of Object.keys(snippetsMergeResult.remote.added)) {
      const previewResult = {
        content: snippetsMergeResult.remote.added[key],
        hasConflicts: false,
        localChange: 0,
        remoteChange: 1
      };
      const localContent = localFileContent[key] ? localFileContent[key].value.toString() : null;
      resourcePreviews.set(key, {
        baseResource: this.h.joinPath(this.g, key).with({ scheme: $4rb, authority: "base" }),
        baseContent: baseSnippets[key] ?? null,
        localResource: this.h.joinPath(this.g, key).with({ scheme: $4rb, authority: "local" }),
        fileContent: localFileContent[key],
        localContent,
        remoteResource: this.h.joinPath(this.g, key).with({ scheme: $4rb, authority: "remote" }),
        remoteContent: null,
        previewResource: this.h.joinPath(this.g, key),
        previewResult,
        localChange: previewResult.localChange,
        remoteChange: previewResult.remoteChange,
        acceptedResource: this.h.joinPath(this.g, key).with({ scheme: $4rb, authority: "accepted" })
      });
    }
    for (const key of Object.keys(snippetsMergeResult.remote.updated)) {
      const previewResult = {
        content: snippetsMergeResult.remote.updated[key],
        hasConflicts: false,
        localChange: 0,
        remoteChange: 2
      };
      const localContent = localFileContent[key] ? localFileContent[key].value.toString() : null;
      resourcePreviews.set(key, {
        baseResource: this.h.joinPath(this.g, key).with({ scheme: $4rb, authority: "base" }),
        baseContent: baseSnippets[key] ?? null,
        localResource: this.h.joinPath(this.g, key).with({ scheme: $4rb, authority: "local" }),
        fileContent: localFileContent[key],
        localContent,
        remoteResource: this.h.joinPath(this.g, key).with({ scheme: $4rb, authority: "remote" }),
        remoteContent: remoteSnippets[key],
        previewResource: this.h.joinPath(this.g, key),
        previewResult,
        localChange: previewResult.localChange,
        remoteChange: previewResult.remoteChange,
        acceptedResource: this.h.joinPath(this.g, key).with({ scheme: $4rb, authority: "accepted" })
      });
    }
    for (const key of snippetsMergeResult.remote.removed) {
      const previewResult = {
        content: null,
        hasConflicts: false,
        localChange: 0,
        remoteChange: 3
      };
      resourcePreviews.set(key, {
        baseResource: this.h.joinPath(this.g, key).with({ scheme: $4rb, authority: "base" }),
        baseContent: baseSnippets[key] ?? null,
        localResource: this.h.joinPath(this.g, key).with({ scheme: $4rb, authority: "local" }),
        fileContent: null,
        localContent: null,
        remoteResource: this.h.joinPath(this.g, key).with({ scheme: $4rb, authority: "remote" }),
        remoteContent: remoteSnippets[key],
        previewResource: this.h.joinPath(this.g, key),
        previewResult,
        localChange: previewResult.localChange,
        remoteChange: previewResult.remoteChange,
        acceptedResource: this.h.joinPath(this.g, key).with({ scheme: $4rb, authority: "accepted" })
      });
    }
    for (const key of snippetsMergeResult.conflicts) {
      const previewResult = {
        content: baseSnippets[key] ?? null,
        hasConflicts: true,
        localChange: localFileContent[key] ? 2 : 1,
        remoteChange: remoteSnippets[key] ? 2 : 1
        /* Change.Added */
      };
      const localContent = localFileContent[key] ? localFileContent[key].value.toString() : null;
      resourcePreviews.set(key, {
        baseResource: this.h.joinPath(this.g, key).with({ scheme: $4rb, authority: "base" }),
        baseContent: baseSnippets[key] ?? null,
        localResource: this.h.joinPath(this.g, key).with({ scheme: $4rb, authority: "local" }),
        fileContent: localFileContent[key] || null,
        localContent,
        remoteResource: this.h.joinPath(this.g, key).with({ scheme: $4rb, authority: "remote" }),
        remoteContent: remoteSnippets[key] || null,
        previewResource: this.h.joinPath(this.g, key),
        previewResult,
        localChange: previewResult.localChange,
        remoteChange: previewResult.remoteChange,
        acceptedResource: this.h.joinPath(this.g, key).with({ scheme: $4rb, authority: "accepted" })
      });
    }
    for (const key of Object.keys(localFileContent)) {
      if (!resourcePreviews.has(key)) {
        const previewResult = {
          content: localFileContent[key] ? localFileContent[key].value.toString() : null,
          hasConflicts: false,
          localChange: 0,
          remoteChange: 0
          /* Change.None */
        };
        const localContent = localFileContent[key] ? localFileContent[key].value.toString() : null;
        resourcePreviews.set(key, {
          baseResource: this.h.joinPath(this.g, key).with({ scheme: $4rb, authority: "base" }),
          baseContent: baseSnippets[key] ?? null,
          localResource: this.h.joinPath(this.g, key).with({ scheme: $4rb, authority: "local" }),
          fileContent: localFileContent[key] || null,
          localContent,
          remoteResource: this.h.joinPath(this.g, key).with({ scheme: $4rb, authority: "remote" }),
          remoteContent: remoteSnippets[key] || null,
          previewResource: this.h.joinPath(this.g, key),
          previewResult,
          localChange: previewResult.localChange,
          remoteChange: previewResult.remoteChange,
          acceptedResource: this.h.joinPath(this.g, key).with({ scheme: $4rb, authority: "accepted" })
        });
      }
    }
    return [...resourcePreviews.values()];
  }
  async resolveContent(uri) {
    if (this.h.isEqualOrParent(uri, this.g.with({ scheme: $4rb, authority: "remote" })) || this.h.isEqualOrParent(uri, this.g.with({ scheme: $4rb, authority: "local" })) || this.h.isEqualOrParent(uri, this.g.with({ scheme: $4rb, authority: "base" })) || this.h.isEqualOrParent(uri, this.g.with({ scheme: $4rb, authority: "accepted" }))) {
      return this.db(uri);
    }
    return null;
  }
  async hasLocalData() {
    try {
      const localSnippets = await this.Hb();
      if (Object.keys(localSnippets).length) {
        return true;
      }
    } catch (error) {
    }
    return false;
  }
  async Cb(resourcePreviews) {
    const local = {};
    for (const resourcePreview of resourcePreviews) {
      if (resourcePreview.fileContent) {
        local[this.h.basename(resourcePreview.localResource)] = resourcePreview.fileContent;
      }
    }
    await this.nb(JSON.stringify(this.Gb(local)));
  }
  async Db(resourcePreviews, force) {
    for (const { fileContent, acceptResult, localResource, remoteResource, localChange } of resourcePreviews) {
      if (localChange !== 0) {
        const key = remoteResource ? this.h.basename(remoteResource) : this.h.basename(localResource);
        const resource = this.h.joinPath(this.vb, key);
        if (localChange === 3) {
          this.O.trace(`${this.D}: Deleting snippet...`, this.h.basename(resource));
          await this.G.del(resource);
          this.O.info(`${this.D}: Deleted snippet`, this.h.basename(resource));
        } else if (localChange === 1) {
          this.O.trace(`${this.D}: Creating snippet...`, this.h.basename(resource));
          await this.G.createFile(resource, $7e.fromString(acceptResult.content), { overwrite: force });
          this.O.info(`${this.D}: Created snippet`, this.h.basename(resource));
        } else {
          this.O.trace(`${this.D}: Updating snippet...`, this.h.basename(resource));
          await this.G.writeFile(resource, $7e.fromString(acceptResult.content), force ? void 0 : fileContent);
          this.O.info(`${this.D}: Updated snippet`, this.h.basename(resource));
        }
      }
    }
  }
  async Eb(resourcePreviews, remoteUserData, forcePush) {
    const currentSnippets = remoteUserData.syncData ? this.Fb(remoteUserData.syncData) : {};
    const newSnippets = $zo(currentSnippets);
    for (const { acceptResult, localResource, remoteResource, remoteChange } of resourcePreviews) {
      if (remoteChange !== 0) {
        const key = localResource ? this.h.basename(localResource) : this.h.basename(remoteResource);
        if (remoteChange === 3) {
          delete newSnippets[key];
        } else {
          newSnippets[key] = acceptResult.content;
        }
      }
    }
    if (!$5gc(currentSnippets, newSnippets)) {
      this.O.trace(`${this.D}: Updating remote snippets...`);
      remoteUserData = await this.mb(JSON.stringify(newSnippets), forcePush ? null : remoteUserData.ref);
      this.O.info(`${this.D}: Updated remote snippets`);
    }
    return remoteUserData;
  }
  Fb(syncData) {
    return $6gc(syncData);
  }
  Gb(snippetsFileContents) {
    const snippets = {};
    for (const key of Object.keys(snippetsFileContents)) {
      snippets[key] = snippetsFileContents[key].value.toString();
    }
    return snippets;
  }
  async Hb() {
    const snippets = {};
    let stat;
    try {
      stat = await this.G.resolve(this.vb);
    } catch (e) {
      if (e instanceof $Pl && e.fileOperationResult === 1) {
        return snippets;
      } else {
        throw e;
      }
    }
    for (const entry of stat.children || []) {
      const resource = entry.resource;
      const extension = this.h.extname(resource);
      if (extension === ".json" || extension === ".code-snippets") {
        const key = this.h.relativePath(this.vb, resource);
        const content = await this.G.readFile(resource);
        snippets[key] = content;
      }
    }
    return snippets;
  }
};
$7gc = __decorate([
  __param(2, $7i),
  __param(3, $ul),
  __param(4, $Dq),
  __param(5, $Mrb),
  __param(6, $Nrb),
  __param(7, $2rb),
  __param(8, $tj),
  __param(9, $Wrb),
  __param(10, $tm),
  __param(11, $5l)
], $7gc);
var $8gc = class $8gc2 extends $lTb {
  constructor(fileService, userDataProfilesService, environmentService, logService, storageService, uriIdentityService) {
    super("snippets", userDataProfilesService, environmentService, logService, fileService, storageService, uriIdentityService);
  }
  async o(remoteUserData) {
    const remoteSnippets = remoteUserData.syncData ? JSON.parse(remoteUserData.syncData.content) : null;
    if (!remoteSnippets) {
      this.j.info("Skipping initializing snippets because remote snippets does not exist.");
      return;
    }
    const isEmpty = await this.i();
    if (!isEmpty) {
      this.j.info("Skipping initializing snippets because local snippets exist.");
      return;
    }
    for (const key of Object.keys(remoteSnippets)) {
      const content = remoteSnippets[key];
      if (content) {
        const resource = this.d.joinPath(this.g.defaultProfile.snippetsHome, key);
        await this.k.createFile(resource, $7e.fromString(content));
        this.j.info("Created snippet", this.d.basename(resource));
      }
    }
    await this.n(remoteUserData);
  }
  async i() {
    try {
      const stat = await this.k.resolve(this.g.defaultProfile.snippetsHome);
      return !stat.children?.length;
    } catch (error) {
      return error.fileOperationResult === 1;
    }
  }
};
$8gc = __decorate([
  __param(0, $ul),
  __param(1, $7l),
  __param(2, $7i),
  __param(3, $2rb),
  __param(4, $Dq),
  __param(5, $5l)
], $8gc);

// out-build/vs/platform/userDataSync/common/tasksSync.js
function $9gc(syncContent, logService) {
  try {
    const parsed = JSON.parse(syncContent);
    return parsed.tasks ?? null;
  } catch (e) {
    logService.error(e);
    return null;
  }
}
var $0gc = class $0gc2 extends $jTb {
  constructor(profile, collection, userDataSyncStoreService, userDataSyncLocalStoreService, logService, configurationService, userDataSyncEnablementService, fileService, environmentService, storageService, telemetryService, uriIdentityService) {
    super(profile.tasksResource, { syncResource: "tasks", profile }, collection, fileService, environmentService, storageService, userDataSyncStoreService, userDataSyncLocalStoreService, userDataSyncEnablementService, telemetryService, logService, configurationService, uriIdentityService);
    this.pb = 1;
    this.Ab = this.h.joinPath(this.g, "tasks.json");
    this.Bb = this.Ab.with({ scheme: $4rb, authority: "base" });
    this.Cb = this.Ab.with({ scheme: $4rb, authority: "local" });
    this.Db = this.Ab.with({ scheme: $4rb, authority: "remote" });
    this.Eb = this.Ab.with({ scheme: $4rb, authority: "accepted" });
  }
  async qb(remoteUserData, lastSyncUserData, isRemoteDataFromCurrentMachine, userDataSyncConfiguration) {
    const remoteContent = remoteUserData.syncData ? $9gc(remoteUserData.syncData.content, this.O) : null;
    lastSyncUserData = lastSyncUserData === null && isRemoteDataFromCurrentMachine ? remoteUserData : lastSyncUserData;
    const lastSyncContent = lastSyncUserData?.syncData ? $9gc(lastSyncUserData.syncData.content, this.O) : null;
    const fileContent = await this.vb();
    let content = null;
    let hasLocalChanged = false;
    let hasRemoteChanged = false;
    let hasConflicts = false;
    if (remoteUserData.syncData) {
      const localContent2 = fileContent ? fileContent.value.toString() : null;
      if (!lastSyncContent || lastSyncContent !== localContent2 || lastSyncContent !== remoteContent) {
        this.O.trace(`${this.D}: Merging remote tasks with local tasks...`);
        const result = merge(localContent2, remoteContent, lastSyncContent);
        content = result.content;
        hasConflicts = result.hasConflicts;
        hasLocalChanged = result.hasLocalChanged;
        hasRemoteChanged = result.hasRemoteChanged;
      }
    } else if (fileContent) {
      this.O.trace(`${this.D}: Remote tasks does not exist. Synchronizing tasks for the first time.`);
      content = fileContent.value.toString();
      hasRemoteChanged = true;
    }
    const previewResult = {
      content: hasConflicts ? lastSyncContent : content,
      localChange: hasLocalChanged ? fileContent ? 2 : 1 : 0,
      remoteChange: hasRemoteChanged ? 2 : 0,
      hasConflicts
    };
    const localContent = fileContent ? fileContent.value.toString() : null;
    return [{
      fileContent,
      baseResource: this.Bb,
      baseContent: lastSyncContent,
      localResource: this.Cb,
      localContent,
      localChange: previewResult.localChange,
      remoteResource: this.Db,
      remoteContent,
      remoteChange: previewResult.remoteChange,
      previewResource: this.Ab,
      previewResult,
      acceptedResource: this.Eb
    }];
  }
  async ub(lastSyncUserData) {
    const lastSyncContent = lastSyncUserData?.syncData ? $9gc(lastSyncUserData.syncData.content, this.O) : null;
    if (lastSyncContent === null) {
      return true;
    }
    const fileContent = await this.vb();
    const localContent = fileContent ? fileContent.value.toString() : null;
    const result = merge(localContent, lastSyncContent, lastSyncContent);
    return result.hasLocalChanged || result.hasRemoteChanged;
  }
  async rb(resourcePreview, token) {
    return resourcePreview.previewResult;
  }
  async sb(resourcePreview, resource, content, token) {
    if (this.h.isEqual(resource, this.Cb)) {
      return {
        content: resourcePreview.fileContent ? resourcePreview.fileContent.value.toString() : null,
        localChange: 0,
        remoteChange: 2
      };
    }
    if (this.h.isEqual(resource, this.Db)) {
      return {
        content: resourcePreview.remoteContent,
        localChange: 2,
        remoteChange: 0
      };
    }
    if (this.h.isEqual(resource, this.Ab)) {
      if (content === void 0) {
        return {
          content: resourcePreview.previewResult.content,
          localChange: resourcePreview.previewResult.localChange,
          remoteChange: resourcePreview.previewResult.remoteChange
        };
      } else {
        return {
          content,
          localChange: 2,
          remoteChange: 2
        };
      }
    }
    throw new Error(`Invalid Resource: ${resource.toString()}`);
  }
  async tb(remoteUserData, lastSyncUserData, resourcePreviews, force) {
    const { fileContent } = resourcePreviews[0][0];
    const { content, localChange, remoteChange } = resourcePreviews[0][1];
    if (localChange === 0 && remoteChange === 0) {
      this.O.info(`${this.D}: No changes found during synchronizing tasks.`);
    }
    if (localChange !== 0) {
      this.O.trace(`${this.D}: Updating local tasks...`);
      if (fileContent) {
        await this.nb(JSON.stringify(this.Kb(fileContent.value.toString())));
      }
      if (content) {
        await this.wb(content, fileContent, force);
      } else {
        await this.xb();
      }
      this.O.info(`${this.D}: Updated local tasks`);
    }
    if (remoteChange !== 0) {
      this.O.trace(`${this.D}: Updating remote tasks...`);
      const remoteContents = JSON.stringify(this.Kb(content));
      remoteUserData = await this.mb(remoteContents, force ? null : remoteUserData.ref);
      this.O.info(`${this.D}: Updated remote tasks`);
    }
    try {
      await this.G.del(this.Ab);
    } catch (e) {
    }
    if (lastSyncUserData?.ref !== remoteUserData.ref) {
      this.O.trace(`${this.D}: Updating last synchronized tasks...`);
      await this.fb(remoteUserData);
      this.O.info(`${this.D}: Updated last synchronized tasks`);
    }
  }
  async hasLocalData() {
    return this.G.exists(this.r);
  }
  async resolveContent(uri) {
    if (this.h.isEqual(this.Db, uri) || this.h.isEqual(this.Bb, uri) || this.h.isEqual(this.Cb, uri) || this.h.isEqual(this.Eb, uri)) {
      return this.db(uri);
    }
    return null;
  }
  Kb(tasks) {
    return tasks ? { tasks } : {};
  }
};
$0gc = __decorate([
  __param(2, $Mrb),
  __param(3, $Nrb),
  __param(4, $2rb),
  __param(5, $tj),
  __param(6, $Wrb),
  __param(7, $ul),
  __param(8, $7i),
  __param(9, $Dq),
  __param(10, $tm),
  __param(11, $5l)
], $0gc);
var $$gc = class $$gc2 extends $lTb {
  constructor(fileService, userDataProfilesService, environmentService, logService, storageService, uriIdentityService) {
    super("tasks", userDataProfilesService, environmentService, logService, fileService, storageService, uriIdentityService);
    this.c = this.g.defaultProfile.tasksResource;
  }
  async o(remoteUserData) {
    const tasksContent = remoteUserData.syncData ? $9gc(remoteUserData.syncData.content, this.j) : null;
    if (!tasksContent) {
      this.j.info("Skipping initializing tasks because remote tasks does not exist.");
      return;
    }
    const isEmpty = await this.p();
    if (!isEmpty) {
      this.j.info("Skipping initializing tasks because local tasks exist.");
      return;
    }
    await this.k.writeFile(this.c, $7e.fromString(tasksContent));
    await this.n(remoteUserData);
  }
  async p() {
    return this.k.exists(this.c);
  }
};
$$gc = __decorate([
  __param(0, $ul),
  __param(1, $7l),
  __param(2, $7i),
  __param(3, $2rb),
  __param(4, $Dq),
  __param(5, $5l)
], $$gc);
function merge(originalLocalContent, originalRemoteContent, baseContent) {
  if (originalLocalContent === null && originalRemoteContent === null && baseContent === null) {
    return { content: null, hasLocalChanged: false, hasRemoteChanged: false, hasConflicts: false };
  }
  if (originalLocalContent === originalRemoteContent) {
    return { content: null, hasLocalChanged: false, hasRemoteChanged: false, hasConflicts: false };
  }
  const localForwarded = baseContent !== originalLocalContent;
  const remoteForwarded = baseContent !== originalRemoteContent;
  if (!localForwarded && !remoteForwarded) {
    return { content: null, hasLocalChanged: false, hasRemoteChanged: false, hasConflicts: false };
  }
  if (localForwarded && !remoteForwarded) {
    return { content: originalLocalContent, hasRemoteChanged: true, hasLocalChanged: false, hasConflicts: false };
  }
  if (remoteForwarded && !localForwarded) {
    return { content: originalRemoteContent, hasLocalChanged: true, hasRemoteChanged: false, hasConflicts: false };
  }
  return { content: originalLocalContent, hasLocalChanged: true, hasRemoteChanged: true, hasConflicts: true };
}

// out-build/vs/platform/userDataSync/common/userDataProfilesManifestMerge.js
function $Ric(local, remote, lastSync, ignored) {
  const localResult = { added: [], removed: [], updated: [] };
  let remoteResult = { added: [], removed: [], updated: [] };
  if (!remote) {
    const added = local.filter(({ id: id2 }) => !ignored.includes(id2));
    if (added.length) {
      remoteResult.added = added;
    } else {
      remoteResult = null;
    }
    return {
      local: localResult,
      remote: remoteResult
    };
  }
  const localToRemote = compare7(local, remote, ignored);
  if (localToRemote.added.length > 0 || localToRemote.removed.length > 0 || localToRemote.updated.length > 0) {
    const baseToLocal = compare7(lastSync, local, ignored);
    const baseToRemote = compare7(lastSync, remote, ignored);
    for (const id2 of baseToRemote.removed) {
      const e = local.find((profile) => profile.id === id2);
      if (e) {
        localResult.removed.push(e);
      }
    }
    for (const id2 of baseToRemote.added) {
      const remoteProfile = remote.find((profile) => profile.id === id2);
      if (baseToLocal.added.includes(id2)) {
        if (localToRemote.updated.includes(id2)) {
          localResult.updated.push(remoteProfile);
        }
      } else {
        localResult.added.push(remoteProfile);
      }
    }
    for (const id2 of baseToRemote.updated) {
      localResult.updated.push(remote.find((profile) => profile.id === id2));
    }
    for (const id2 of baseToLocal.added) {
      if (!baseToRemote.added.includes(id2)) {
        remoteResult.added.push(local.find((profile) => profile.id === id2));
      }
    }
    for (const id2 of baseToLocal.updated) {
      if (baseToRemote.removed.includes(id2)) {
        continue;
      }
      if (!baseToRemote.updated.includes(id2)) {
        remoteResult.updated.push(local.find((profile) => profile.id === id2));
      }
    }
    for (const id2 of baseToLocal.removed) {
      const removedProfile = remote.find((profile) => profile.id === id2);
      if (removedProfile) {
        remoteResult.removed.push(removedProfile);
      }
    }
  }
  if (remoteResult.added.length === 0 && remoteResult.removed.length === 0 && remoteResult.updated.length === 0) {
    remoteResult = null;
  }
  return { local: localResult, remote: remoteResult };
}
function compare7(from, to, ignoredProfiles) {
  from = from ? from.filter(({ id: id2 }) => !ignoredProfiles.includes(id2)) : [];
  to = to.filter(({ id: id2 }) => !ignoredProfiles.includes(id2));
  const fromKeys = from.map(({ id: id2 }) => id2);
  const toKeys = to.map(({ id: id2 }) => id2);
  const added = toKeys.filter((key) => !fromKeys.includes(key));
  const removed = fromKeys.filter((key) => !toKeys.includes(key));
  const updated = [];
  for (const { id: id2, name, shortName, icon, useDefaultFlags } of from) {
    if (removed.includes(id2)) {
      continue;
    }
    const toProfile = to.find((p) => p.id === id2);
    if (!toProfile || toProfile.name !== name || toProfile.shortName !== shortName || toProfile.icon !== icon || !$Do(toProfile.useDefaultFlags, useDefaultFlags)) {
      updated.push(id2);
    }
  }
  return { added, removed, updated };
}

// out-build/vs/platform/userDataSync/common/userDataProfilesManifestSync.js
var $Sic = class $Sic2 extends $iTb {
  constructor(profile, collection, vb, fileService, environmentService, storageService, userDataSyncStoreService, userDataSyncLocalStoreService, logService, configurationService, userDataSyncEnablementService, telemetryService, uriIdentityService) {
    super({ syncResource: "profiles", profile }, collection, fileService, environmentService, storageService, userDataSyncStoreService, userDataSyncLocalStoreService, userDataSyncEnablementService, telemetryService, logService, configurationService, uriIdentityService);
    this.vb = vb;
    this.pb = 2;
    this.previewResource = this.h.joinPath(this.g, "profiles.json");
    this.baseResource = this.previewResource.with({ scheme: $4rb, authority: "base" });
    this.localResource = this.previewResource.with({ scheme: $4rb, authority: "local" });
    this.remoteResource = this.previewResource.with({ scheme: $4rb, authority: "remote" });
    this.acceptedResource = this.previewResource.with({ scheme: $4rb, authority: "accepted" });
    this.B(vb.onDidChangeProfiles(() => this.Q()));
  }
  async getLastSyncedProfiles() {
    const lastSyncUserData = await this.getLastSyncUserData();
    return lastSyncUserData?.syncData ? $Uic(lastSyncUserData.syncData) : null;
  }
  async getRemoteSyncedProfiles(manifest) {
    const lastSyncUserData = await this.getLastSyncUserData();
    const remoteUserData = await this.X(manifest, lastSyncUserData);
    return remoteUserData?.syncData ? $Uic(remoteUserData.syncData) : null;
  }
  async qb(remoteUserData, lastSyncUserData, isRemoteDataFromCurrentMachine) {
    if (!this.vb.isEnabled()) {
      throw new $Rrb(
        "Cannot sync profiles because they are disabled",
        "LocalError"
        /* UserDataSyncErrorCode.LocalError */
      );
    }
    const remoteProfiles = remoteUserData.syncData ? $Uic(remoteUserData.syncData) : null;
    const lastSyncProfiles = lastSyncUserData?.syncData ? $Uic(lastSyncUserData.syncData) : null;
    const localProfiles = this.Db();
    const { local, remote } = $Ric(localProfiles, remoteProfiles, lastSyncProfiles, []);
    const previewResult = {
      local,
      remote,
      content: lastSyncProfiles ? this.Eb(lastSyncProfiles) : null,
      localChange: local.added.length > 0 || local.removed.length > 0 || local.updated.length > 0 ? 2 : 0,
      remoteChange: remote !== null ? 2 : 0
    };
    const localContent = $Tic(localProfiles, false);
    return [{
      baseResource: this.baseResource,
      baseContent: lastSyncProfiles ? this.Eb(lastSyncProfiles) : null,
      localResource: this.localResource,
      localContent,
      remoteResource: this.remoteResource,
      remoteContent: remoteProfiles ? this.Eb(remoteProfiles) : null,
      remoteProfiles,
      previewResource: this.previewResource,
      previewResult,
      localChange: previewResult.localChange,
      remoteChange: previewResult.remoteChange,
      acceptedResource: this.acceptedResource
    }];
  }
  async ub(lastSyncUserData) {
    const lastSyncProfiles = lastSyncUserData?.syncData ? $Uic(lastSyncUserData.syncData) : null;
    const localProfiles = this.Db();
    const { remote } = $Ric(localProfiles, lastSyncProfiles, lastSyncProfiles, []);
    return !!remote?.added.length || !!remote?.removed.length || !!remote?.updated.length;
  }
  async rb(resourcePreview, token) {
    return { ...resourcePreview.previewResult, hasConflicts: false };
  }
  async sb(resourcePreview, resource, content, token) {
    if (this.h.isEqual(resource, this.localResource)) {
      return this.Ab(resourcePreview);
    }
    if (this.h.isEqual(resource, this.remoteResource)) {
      return this.Bb(resourcePreview);
    }
    if (this.h.isEqual(resource, this.previewResource)) {
      return resourcePreview.previewResult;
    }
    throw new Error(`Invalid Resource: ${resource.toString()}`);
  }
  async Ab(resourcePreview) {
    const localProfiles = this.Db();
    const mergeResult = $Ric(localProfiles, null, null, []);
    const { local, remote } = mergeResult;
    return {
      content: resourcePreview.localContent,
      local,
      remote,
      localChange: local.added.length > 0 || local.removed.length > 0 || local.updated.length > 0 ? 2 : 0,
      remoteChange: remote !== null ? 2 : 0
    };
  }
  async Bb(resourcePreview) {
    const remoteProfiles = resourcePreview.remoteContent ? JSON.parse(resourcePreview.remoteContent) : null;
    const lastSyncProfiles = [];
    const localProfiles = [];
    for (const profile of this.Db()) {
      const remoteProfile = remoteProfiles?.find((remoteProfile2) => remoteProfile2.id === profile.id);
      if (remoteProfile) {
        lastSyncProfiles.push({ id: profile.id, name: profile.name, collection: remoteProfile.collection });
        localProfiles.push(profile);
      }
    }
    if (remoteProfiles !== null) {
      const mergeResult = $Ric(localProfiles, remoteProfiles, lastSyncProfiles, []);
      const { local, remote } = mergeResult;
      return {
        content: resourcePreview.remoteContent,
        local,
        remote,
        localChange: local.added.length > 0 || local.removed.length > 0 || local.updated.length > 0 ? 2 : 0,
        remoteChange: remote !== null ? 2 : 0
      };
    } else {
      return {
        content: resourcePreview.remoteContent,
        local: { added: [], removed: [], updated: [] },
        remote: null,
        localChange: 0,
        remoteChange: 0
      };
    }
  }
  async tb(remoteUserData, lastSyncUserData, resourcePreviews, force) {
    const { local, remote, localChange, remoteChange } = resourcePreviews[0][1];
    if (localChange === 0 && remoteChange === 0) {
      this.O.info(`${this.D}: No changes found during synchronizing profiles.`);
    }
    const remoteProfiles = resourcePreviews[0][0].remoteProfiles || [];
    if (remoteProfiles.length + (remote?.added.length ?? 0) - (remote?.removed.length ?? 0) > 20) {
      throw new $Rrb(
        "Too many profiles to sync. Please remove some profiles and try again.",
        "LocalTooManyProfiles"
        /* UserDataSyncErrorCode.LocalTooManyProfiles */
      );
    }
    if (localChange !== 0) {
      await this.nb($Tic(this.Db(), false));
      await Promise.all(local.removed.map(async (profile) => {
        this.O.trace(`${this.D}: Removing '${profile.name}' profile...`);
        await this.vb.removeProfile(profile);
        this.O.info(`${this.D}: Removed profile '${profile.name}'.`);
      }));
      await Promise.all(local.added.map(async (profile) => {
        this.O.trace(`${this.D}: Creating '${profile.name}' profile...`);
        await this.vb.createProfile(profile.id, profile.name, { shortName: profile.shortName, icon: profile.icon, useDefaultFlags: profile.useDefaultFlags });
        this.O.info(`${this.D}: Created profile '${profile.name}'.`);
      }));
      await Promise.all(local.updated.map(async (profile) => {
        const localProfile = this.vb.profiles.find((p) => p.id === profile.id);
        if (localProfile) {
          this.O.trace(`${this.D}: Updating '${profile.name}' profile...`);
          await this.vb.updateProfile(localProfile, { name: profile.name, shortName: profile.shortName, icon: profile.icon, useDefaultFlags: profile.useDefaultFlags });
          this.O.info(`${this.D}: Updated profile '${profile.name}'.`);
        } else {
          this.O.info(`${this.D}: Could not find profile with id '${profile.id}' to update.`);
        }
      }));
    }
    if (remoteChange !== 0) {
      this.O.trace(`${this.D}: Updating remote profiles...`);
      const addedCollections = [];
      const canAddRemoteProfiles = remoteProfiles.length + (remote?.added.length ?? 0) <= 20;
      if (canAddRemoteProfiles) {
        for (const profile of remote?.added || []) {
          const collection = await this.J.createCollection(this.F);
          addedCollections.push(collection);
          remoteProfiles.push({ id: profile.id, name: profile.name, collection, shortName: profile.shortName, icon: profile.icon, useDefaultFlags: profile.useDefaultFlags });
        }
      } else {
        this.O.info(`${this.D}: Could not create remote profiles as there are too many profiles.`);
      }
      for (const profile of remote?.removed || []) {
        remoteProfiles.splice(remoteProfiles.findIndex(({ id: id2 }) => profile.id === id2), 1);
      }
      for (const profile of remote?.updated || []) {
        const profileToBeUpdated = remoteProfiles.find(({ id: id2 }) => profile.id === id2);
        if (profileToBeUpdated) {
          remoteProfiles.splice(remoteProfiles.indexOf(profileToBeUpdated), 1, { ...profileToBeUpdated, id: profile.id, name: profile.name, shortName: profile.shortName, icon: profile.icon, useDefaultFlags: profile.useDefaultFlags });
        }
      }
      try {
        remoteUserData = await this.updateRemoteProfiles(remoteProfiles, force ? null : remoteUserData.ref);
        this.O.info(`${this.D}: Updated remote profiles.${canAddRemoteProfiles && remote?.added.length ? ` Added: ${JSON.stringify(remote.added.map((e) => e.name))}.` : ""}${remote?.updated.length ? ` Updated: ${JSON.stringify(remote.updated.map((e) => e.name))}.` : ""}${remote?.removed.length ? ` Removed: ${JSON.stringify(remote.removed.map((e) => e.name))}.` : ""}`);
      } catch (error) {
        if (addedCollections.length) {
          this.O.info(`${this.D}: Failed to update remote profiles. Cleaning up added collections...`);
          for (const collection of addedCollections) {
            await this.J.deleteCollection(collection, this.F);
          }
        }
        throw error;
      }
      for (const profile of remote?.removed || []) {
        await this.J.deleteCollection(profile.collection, this.F);
      }
    }
    if (lastSyncUserData?.ref !== remoteUserData.ref) {
      this.O.trace(`${this.D}: Updating last synchronized profiles...`);
      await this.fb(remoteUserData);
      this.O.info(`${this.D}: Updated last synchronized profiles.`);
    }
  }
  async updateRemoteProfiles(profiles, ref) {
    return this.mb(this.Eb(profiles), ref);
  }
  async hasLocalData() {
    return this.Db().length > 0;
  }
  async resolveContent(uri) {
    if (this.h.isEqual(this.remoteResource, uri) || this.h.isEqual(this.baseResource, uri) || this.h.isEqual(this.localResource, uri) || this.h.isEqual(this.acceptedResource, uri)) {
      const content = await this.db(uri);
      return content ? $ro(JSON.parse(content), {}) : content;
    }
    return null;
  }
  Db() {
    return this.vb.profiles.filter((p) => !p.isDefault && !p.isTransient);
  }
  Eb(profiles) {
    return JSON.stringify([...profiles].sort((a, b) => a.name.localeCompare(b.name)));
  }
};
$Sic = __decorate([
  __param(2, $7l),
  __param(3, $ul),
  __param(4, $7i),
  __param(5, $Dq),
  __param(6, $Mrb),
  __param(7, $Nrb),
  __param(8, $2rb),
  __param(9, $tj),
  __param(10, $Wrb),
  __param(11, $tm),
  __param(12, $5l)
], $Sic);
function $Tic(profiles, format2) {
  const result = [...profiles].sort((a, b) => a.name.localeCompare(b.name)).map((p) => ({ id: p.id, name: p.name }));
  return format2 ? $ro(result, {}) : JSON.stringify(result);
}
function $Uic(syncData) {
  return JSON.parse(syncData.content);
}

// out-build/vs/platform/userDataSync/common/userDataSyncService.js
var LAST_SYNC_TIME_KEY = "sync.lastSyncTime";
var $Vic = class $Vic2 extends $0c {
  get status() {
    return this.f;
  }
  get conflicts() {
    return this.j;
  }
  get lastSyncTime() {
    return this.t;
  }
  constructor(C, D, F, G, H, I, J, L, M, N, O) {
    super();
    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.f = "uninitialized";
    this.g = this.B(new $De());
    this.onDidChangeStatus = this.g.event;
    this.h = this.B(new $De());
    this.onDidChangeLocal = this.h.event;
    this.j = [];
    this.m = this.B(new $De());
    this.onDidChangeConflicts = this.m.event;
    this.n = [];
    this.r = this.B(new $De());
    this.onSyncErrors = this.r.event;
    this.t = void 0;
    this.u = this.B(new $De());
    this.onDidChangeLastSyncTime = this.u.event;
    this.w = this.B(new $De());
    this.onDidResetLocal = this.w.event;
    this.y = this.B(new $De());
    this.onDidResetRemote = this.y.event;
    this.z = /* @__PURE__ */ new Map();
    this.f = F.userDataSyncStore ? "idle" : "uninitialized";
    this.t = this.J.getNumber(LAST_SYNC_TIME_KEY, -1, void 0);
    this.B($8c(() => this.cb()));
    this.B(new $_h(
      () => this.W(),
      5 * 1e3
      /* after 5s */
    )).schedule();
  }
  async createSyncTask(manifest, disableCache) {
    this.db();
    this.H.info("Sync started.");
    const startTime = (/* @__PURE__ */ new Date()).getTime();
    const executionId = $jh();
    try {
      const syncHeaders = $Qrb(executionId);
      if (disableCache) {
        syncHeaders["Cache-Control"] = "no-cache";
      }
      manifest = await this.D.manifest(manifest, syncHeaders);
    } catch (error) {
      const userDataSyncError = $Rrb.toUserDataSyncError(error);
      reportUserDataSyncError(userDataSyncError, executionId, this.F, this.I);
      throw userDataSyncError;
    }
    const executed = false;
    const that = this;
    let cancellablePromise;
    return {
      manifest,
      async run() {
        if (executed) {
          throw new Error("Can run a task only once");
        }
        cancellablePromise = $Mh((token) => that.P(manifest, false, executionId, token));
        await cancellablePromise.finally(() => cancellablePromise = void 0);
        that.H.info(`Sync done. Took ${(/* @__PURE__ */ new Date()).getTime() - startTime}ms`);
        that.ab();
      },
      stop() {
        cancellablePromise?.cancel();
        return that.U();
      }
    };
  }
  async createManualSyncTask() {
    this.db();
    if (this.L.isEnabled()) {
      throw new $Rrb(
        "Cannot start manual sync when sync is enabled",
        "LocalError"
        /* UserDataSyncErrorCode.LocalError */
      );
    }
    this.H.info("Sync started.");
    const startTime = (/* @__PURE__ */ new Date()).getTime();
    const executionId = $jh();
    const syncHeaders = $Qrb(executionId);
    let manifest;
    try {
      manifest = await this.D.manifest(null, syncHeaders);
    } catch (error) {
      const userDataSyncError = $Rrb.toUserDataSyncError(error);
      reportUserDataSyncError(userDataSyncError, executionId, this.F, this.I);
      throw userDataSyncError;
    }
    await this.resetLocal();
    const that = this;
    const cancellableToken = new $Pe();
    return {
      id: executionId,
      async merge() {
        return that.P(manifest, true, executionId, cancellableToken.token);
      },
      async apply() {
        try {
          try {
            await that.R(manifest, executionId, cancellableToken.token);
          } catch (error) {
            if ($Rrb.toUserDataSyncError(error).code === "MethodNotFound") {
              that.H.info("Client is making invalid requests. Cleaning up data...");
              await that.cleanUpRemoteData();
              that.H.info("Applying manual sync again...");
              await that.R(manifest, executionId, cancellableToken.token);
            } else {
              throw error;
            }
          }
        } catch (error) {
          that.H.error(error);
          throw error;
        }
        that.H.info(`Sync done. Took ${(/* @__PURE__ */ new Date()).getTime() - startTime}ms`);
        that.ab();
      },
      async stop() {
        cancellableToken.cancel();
        await that.U();
        await that.resetLocal();
      }
    };
  }
  async P(manifest, merge2, executionId, token) {
    this.n = [];
    try {
      if (this.status !== "hasConflicts") {
        this.Z(
          "syncing"
          /* SyncStatus.Syncing */
        );
      }
      const defaultProfileSynchronizer = this.getOrCreateActiveProfileSynchronizer(this.M.defaultProfile, void 0);
      this.n.push(...await this.S(defaultProfileSynchronizer, manifest, merge2, executionId, token));
      const userDataProfileManifestSynchronizer = defaultProfileSynchronizer.enabled.find(
        (s) => s.resource === "profiles"
        /* SyncResource.Profiles */
      );
      if (userDataProfileManifestSynchronizer) {
        const syncProfiles = await userDataProfileManifestSynchronizer.getLastSyncedProfiles() || [];
        if (token.isCancellationRequested) {
          return;
        }
        await this.Q(syncProfiles, manifest, merge2, executionId, token);
      }
    } finally {
      if (this.status !== "hasConflicts") {
        this.Z(
          "idle"
          /* SyncStatus.Idle */
        );
      }
      this.r.fire(this.n);
    }
  }
  async Q(remoteProfiles, manifest, merge2, executionId, token) {
    for (const syncProfile of remoteProfiles) {
      if (token.isCancellationRequested) {
        return;
      }
      const profile = this.M.profiles.find((p) => p.id === syncProfile.id);
      if (!profile) {
        this.H.error(`Profile with id:${syncProfile.id} and name: ${syncProfile.name} does not exist locally to sync.`);
        continue;
      }
      this.H.info("Syncing profile.", syncProfile.name);
      const profileSynchronizer = this.getOrCreateActiveProfileSynchronizer(profile, syncProfile);
      this.n.push(...await this.S(profileSynchronizer, manifest, merge2, executionId, token));
    }
    for (const [key, profileSynchronizerItem] of this.z.entries()) {
      if (this.M.profiles.some((p) => p.id === profileSynchronizerItem[0].profile.id)) {
        continue;
      }
      await profileSynchronizerItem[0].resetLocal();
      profileSynchronizerItem[1].dispose();
      this.z.delete(key);
    }
  }
  async R(manifest, executionId, token) {
    const profileSynchronizers = this.bb();
    for (const profileSynchronizer of profileSynchronizers) {
      if (token.isCancellationRequested) {
        return;
      }
      await profileSynchronizer.apply(executionId, token);
    }
    const defaultProfileSynchronizer = profileSynchronizers.find((s) => s.profile.isDefault);
    if (!defaultProfileSynchronizer) {
      return;
    }
    const userDataProfileManifestSynchronizer = defaultProfileSynchronizer.enabled.find(
      (s) => s.resource === "profiles"
      /* SyncResource.Profiles */
    );
    if (!userDataProfileManifestSynchronizer) {
      return;
    }
    const remoteProfiles = await userDataProfileManifestSynchronizer.getRemoteSyncedProfiles(manifest?.latest ?? null) || [];
    const remoteProfilesToSync = remoteProfiles.filter((remoteProfile) => profileSynchronizers.every((s) => s.profile.id !== remoteProfile.id));
    if (remoteProfilesToSync.length) {
      await this.Q(remoteProfilesToSync, manifest, false, executionId, token);
    }
  }
  async S(profileSynchronizer, manifest, merge2, executionId, token) {
    const errors = await profileSynchronizer.sync(manifest, merge2, executionId, token);
    return errors.map(([syncResource, error]) => ({ profile: profileSynchronizer.profile, syncResource, error }));
  }
  async U() {
    if (this.status !== "idle") {
      await Promise.allSettled(this.bb().map((profileSynchronizer) => profileSynchronizer.stop()));
    }
  }
  async resolveContent(resource) {
    const content = await this.N.resolveContent(resource);
    if (content) {
      return content;
    }
    for (const profileSynchronizer of this.bb()) {
      for (const synchronizer of profileSynchronizer.enabled) {
        const content2 = await synchronizer.resolveContent(resource);
        if (content2) {
          return content2;
        }
      }
    }
    return null;
  }
  async replace(syncResourceHandle) {
    this.db();
    const profileSyncResource = this.N.resolveUserDataSyncResource(syncResourceHandle);
    if (!profileSyncResource) {
      return;
    }
    const content = await this.resolveContent(syncResourceHandle.uri);
    if (!content) {
      return;
    }
    await this.X(profileSyncResource.profile, async (synchronizer) => {
      if (profileSyncResource.syncResource === synchronizer.resource) {
        await synchronizer.replace(content);
        return true;
      }
      return void 0;
    });
    return;
  }
  async accept(syncResource, resource, content, apply) {
    this.db();
    await this.X(syncResource.profile, async (synchronizer) => {
      if (syncResource.syncResource === synchronizer.resource) {
        await synchronizer.accept(resource, content);
        if (apply) {
          await synchronizer.apply($Eg(apply) ? false : apply.force, $Qrb($jh()));
        }
        return true;
      }
      return void 0;
    });
  }
  async hasLocalData() {
    const result = await this.X(this.M.defaultProfile, async (synchronizer) => {
      if (synchronizer.resource !== "globalState" && await synchronizer.hasLocalData()) {
        return true;
      }
      return void 0;
    });
    return !!result;
  }
  async hasPreviouslySynced() {
    const result = await this.X(this.M.defaultProfile, async (synchronizer) => {
      if (await synchronizer.hasPreviouslySynced()) {
        return true;
      }
      return void 0;
    });
    return !!result;
  }
  async reset() {
    this.db();
    await this.resetRemote();
    await this.resetLocal();
  }
  async resetRemote() {
    this.db();
    try {
      await this.D.clear();
      this.H.info("Cleared data on server");
    } catch (e) {
      this.H.error(e);
    }
    this.y.fire();
  }
  async resetLocal() {
    this.db();
    this.t = void 0;
    this.J.remove(
      LAST_SYNC_TIME_KEY,
      -1
      /* StorageScope.APPLICATION */
    );
    for (const [synchronizer] of this.z.values()) {
      try {
        await synchronizer.resetLocal();
      } catch (e) {
        this.H.error(e);
      }
    }
    this.cb();
    this.w.fire();
    this.H.info("Did reset the local sync state.");
  }
  async W() {
    const allKeys = this.J.keys(
      -1,
      1
      /* StorageTarget.MACHINE */
    );
    const lastSyncProfileKeys = [];
    for (const key of allKeys) {
      if (!key.endsWith(".lastSyncUserData")) {
        continue;
      }
      const segments = key.split(".");
      if (segments.length === 3) {
        lastSyncProfileKeys.push([key, segments[0]]);
      }
    }
    if (!lastSyncProfileKeys.length) {
      return;
    }
    const disposables = new $9c();
    try {
      let defaultProfileSynchronizer = this.z.get(this.M.defaultProfile.id)?.[0];
      if (!defaultProfileSynchronizer) {
        defaultProfileSynchronizer = disposables.add(this.G.createInstance(ProfileSynchronizer, this.M.defaultProfile, void 0));
      }
      const userDataProfileManifestSynchronizer = defaultProfileSynchronizer.enabled.find(
        (s) => s.resource === "profiles"
        /* SyncResource.Profiles */
      );
      if (!userDataProfileManifestSynchronizer) {
        return;
      }
      const lastSyncedProfiles = await userDataProfileManifestSynchronizer.getLastSyncedProfiles();
      const lastSyncedCollections = lastSyncedProfiles?.map((p) => p.collection) ?? [];
      for (const [key, collection] of lastSyncProfileKeys) {
        if (!lastSyncedCollections.includes(collection)) {
          this.H.info(`Removing last sync state for stale profile: ${collection}`);
          this.J.remove(
            key,
            -1
            /* StorageScope.APPLICATION */
          );
        }
      }
    } finally {
      disposables.dispose();
    }
  }
  async cleanUpRemoteData() {
    const remoteProfiles = await this.N.getRemoteSyncedProfiles();
    const remoteProfileCollections = remoteProfiles.map((profile) => profile.collection);
    const allCollections = await this.D.getAllCollections();
    const redundantCollections = allCollections.filter((c) => !remoteProfileCollections.includes(c));
    if (redundantCollections.length) {
      this.H.info(`Deleting ${redundantCollections.length} redundant collections on server`);
      await Promise.allSettled(redundantCollections.map((collectionId) => this.D.deleteCollection(collectionId)));
      this.H.info(`Deleted redundant collections on server`);
    }
    const updatedRemoteProfiles = remoteProfiles.filter((profile) => allCollections.includes(profile.collection));
    if (updatedRemoteProfiles.length !== remoteProfiles.length) {
      const profileManifestSynchronizer = this.G.createInstance($Sic, this.M.defaultProfile, void 0);
      try {
        this.H.info("Resetting the last synced state of profiles");
        await profileManifestSynchronizer.resetLocal();
        this.H.info("Did reset the last synced state of profiles");
        this.H.info(`Updating remote profiles with invalid collections on server`);
        await profileManifestSynchronizer.updateRemoteProfiles(updatedRemoteProfiles, null);
        this.H.info(`Updated remote profiles on server`);
      } finally {
        profileManifestSynchronizer.dispose();
      }
    }
  }
  async saveRemoteActivityData(location) {
    this.db();
    const data = await this.D.getActivityData();
    await this.C.writeFile(location, data);
  }
  async extractActivityData(activityDataResource, location) {
    const content = (await this.C.readFile(activityDataResource)).value.toString();
    const activityData = JSON.parse(content);
    if (activityData.resources) {
      for (const resource in activityData.resources) {
        for (const version of activityData.resources[resource]) {
          await this.O.writeResource(resource, version.content, new Date(version.created * 1e3), void 0, location);
        }
      }
    }
    if (activityData.collections) {
      for (const collection in activityData.collections) {
        for (const resource in activityData.collections[collection].resources) {
          for (const version of activityData.collections[collection].resources?.[resource] ?? []) {
            await this.O.writeResource(resource, version.content, new Date(version.created * 1e3), collection, location);
          }
        }
      }
    }
  }
  async X(profile, action) {
    const disposables = new $9c();
    try {
      const activeProfileSyncronizer = this.z.get(profile.id);
      if (activeProfileSyncronizer) {
        const result = await this.Y(activeProfileSyncronizer[0], action, disposables);
        return $Fg(result) ? null : result;
      }
      if (profile.isDefault) {
        const defaultProfileSynchronizer = disposables.add(this.G.createInstance(ProfileSynchronizer, profile, void 0));
        const result = await this.Y(defaultProfileSynchronizer, action, disposables);
        return $Fg(result) ? null : result;
      }
      if (this.M.isEnabled()) {
        return null;
      }
      const userDataProfileManifestSynchronizer = disposables.add(this.G.createInstance($Sic, profile, void 0));
      const manifest = await this.D.manifest(null);
      const syncProfiles = await userDataProfileManifestSynchronizer.getRemoteSyncedProfiles(manifest?.latest ?? null) || [];
      const syncProfile = syncProfiles.find((syncProfile2) => syncProfile2.id === profile.id);
      if (syncProfile) {
        const profileSynchronizer = disposables.add(this.G.createInstance(ProfileSynchronizer, profile, syncProfile.collection));
        const result = await this.Y(profileSynchronizer, action, disposables);
        return $Fg(result) ? null : result;
      }
      return null;
    } finally {
      disposables.dispose();
    }
  }
  async Y(profileSynchronizer, action, disposables) {
    const allSynchronizers = [...profileSynchronizer.enabled, ...profileSynchronizer.disabled.reduce((synchronizers, syncResource) => {
      if (syncResource !== "workspaceState") {
        synchronizers.push(disposables.add(profileSynchronizer.createSynchronizer(syncResource)));
      }
      return synchronizers;
    }, [])];
    for (const synchronizer of allSynchronizers) {
      const result = await action(synchronizer);
      if (!$Fg(result)) {
        return result;
      }
    }
    return void 0;
  }
  Z(status) {
    const oldStatus = this.f;
    if (this.f !== status) {
      this.f = status;
      this.g.fire(status);
      if (oldStatus === "hasConflicts") {
        this.ab();
      }
    }
  }
  $() {
    const conflicts = this.bb().map((synchronizer) => synchronizer.conflicts).flat();
    if (!$Hb(this.j, conflicts, (a, b) => a.profile.id === b.profile.id && a.syncResource === b.syncResource && $Hb(a.conflicts, b.conflicts, (a2, b2) => $th(a2.previewResource, b2.previewResource)))) {
      this.j = conflicts;
      this.m.fire(conflicts);
    }
  }
  ab() {
    if (this.status === "idle") {
      this.t = (/* @__PURE__ */ new Date()).getTime();
      this.J.store(
        LAST_SYNC_TIME_KEY,
        this.t,
        -1,
        1
        /* StorageTarget.MACHINE */
      );
      this.u.fire(this.t);
    }
  }
  getOrCreateActiveProfileSynchronizer(profile, syncProfile) {
    let activeProfileSynchronizer = this.z.get(profile.id);
    if (activeProfileSynchronizer && activeProfileSynchronizer[0].collection !== syncProfile?.collection) {
      this.H.error("Profile synchronizer collection does not match with the remote sync profile collection");
      activeProfileSynchronizer[1].dispose();
      activeProfileSynchronizer = void 0;
      this.z.delete(profile.id);
    }
    if (!activeProfileSynchronizer) {
      const disposables = new $9c();
      const profileSynchronizer = disposables.add(this.G.createInstance(ProfileSynchronizer, profile, syncProfile?.collection));
      disposables.add(profileSynchronizer.onDidChangeStatus((e) => this.Z(e)));
      disposables.add(profileSynchronizer.onDidChangeConflicts((conflicts) => this.$()));
      disposables.add(profileSynchronizer.onDidChangeLocal((e) => this.h.fire(e)));
      this.z.set(profile.id, activeProfileSynchronizer = [profileSynchronizer, disposables]);
    }
    return activeProfileSynchronizer[0];
  }
  bb() {
    const profileSynchronizers = [];
    for (const [profileSynchronizer] of this.z.values()) {
      profileSynchronizers.push(profileSynchronizer);
    }
    return profileSynchronizers;
  }
  cb() {
    this.z.forEach(([, disposable]) => disposable.dispose());
    this.z.clear();
  }
  db() {
    if (!this.F.userDataSyncStore) {
      throw new Error("Not enabled");
    }
  }
};
$Vic = __decorate([
  __param(0, $ul),
  __param(1, $Mrb),
  __param(2, $Lrb),
  __param(3, $Yi),
  __param(4, $2rb),
  __param(5, $tm),
  __param(6, $Dq),
  __param(7, $Wrb),
  __param(8, $7l),
  __param(9, $Yrb),
  __param(10, $Nrb)
], $Vic);
var ProfileSynchronizer = class ProfileSynchronizer2 extends $0c {
  get enabled() {
    return this.f.sort((a, b) => a[1] - b[1]).map(([synchronizer]) => synchronizer);
  }
  get disabled() {
    return $Irb.filter((syncResource) => !this.r.isResourceEnabled(syncResource));
  }
  get status() {
    return this.g;
  }
  get conflicts() {
    return this.m;
  }
  constructor(profile, collection, r, t, u, w, y, z, C, D) {
    super();
    this.profile = profile;
    this.collection = collection;
    this.r = r;
    this.t = t;
    this.u = u;
    this.w = w;
    this.y = y;
    this.z = z;
    this.C = C;
    this.D = D;
    this.f = [];
    this.g = "idle";
    this.h = this.B(new $De());
    this.onDidChangeStatus = this.h.event;
    this.j = this.B(new $De());
    this.onDidChangeLocal = this.j.event;
    this.m = [];
    this.n = this.B(new $De());
    this.onDidChangeConflicts = this.n.event;
    this.B(r.onDidChangeResourceEnablement(([syncResource, enablement]) => this.F(syncResource, enablement)));
    this.B($8c(() => this.f.splice(0, this.f.length).forEach(([, , disposable]) => disposable.dispose())));
    for (const syncResource of $Irb) {
      if (r.isResourceEnabled(syncResource)) {
        this.G(syncResource);
      }
    }
  }
  F(syncResource, enabled) {
    if (enabled) {
      this.G(syncResource);
    } else {
      this.H(syncResource);
    }
  }
  G(syncResource) {
    if (this.f.some(([synchronizer2]) => synchronizer2.resource === syncResource)) {
      return;
    }
    if (syncResource === "extensions" && !this.u.isEnabled()) {
      this.z.info("Skipping extensions sync because gallery is not configured");
      return;
    }
    if (syncResource === "profiles") {
      if (!this.profile.isDefault) {
        return;
      }
      if (!this.C.isEnabled()) {
        return;
      }
    }
    if (syncResource === "workspaceState") {
      return;
    }
    if (syncResource !== "profiles" && this.profile.useDefaultFlags?.[syncResource]) {
      this.z.debug(`Skipping syncing ${syncResource} in ${this.profile.name} because it is already synced by default profile`);
      return;
    }
    const disposables = new $9c();
    const synchronizer = disposables.add(this.createSynchronizer(syncResource));
    disposables.add(synchronizer.onDidChangeStatus(() => this.L()));
    disposables.add(synchronizer.onDidChangeConflicts(() => this.M()));
    disposables.add(synchronizer.onDidChangeLocal(() => this.j.fire(syncResource)));
    const order = this.N(syncResource);
    this.f.push([synchronizer, order, disposables]);
  }
  H(syncResource) {
    const index = this.f.findIndex(([synchronizer]) => synchronizer.resource === syncResource);
    if (index !== -1) {
      const [[synchronizer, , disposable]] = this.f.splice(index, 1);
      disposable.dispose();
      this.L();
      synchronizer.stop().then(null, (error) => this.z.error(error));
    }
  }
  createSynchronizer(syncResource) {
    switch (syncResource) {
      case "settings":
        return this.t.createInstance($2gc, this.profile, this.collection);
      case "keybindings":
        return this.t.createInstance($Ygc, this.profile, this.collection);
      case "snippets":
        return this.t.createInstance($7gc, this.profile, this.collection);
      case "tasks":
        return this.t.createInstance($0gc, this.profile, this.collection);
      case "globalState":
        return this.t.createInstance($oTb, this.profile, this.collection);
      case "extensions":
        return this.t.createInstance($Tgc, this.profile, this.collection);
      case "profiles":
        return this.t.createInstance($Sic, this.profile, this.collection);
    }
  }
  async sync(manifest, merge2, executionId, token) {
    if (token.isCancellationRequested) {
      return [];
    }
    const synchronizers = this.enabled;
    if (!synchronizers.length) {
      return [];
    }
    try {
      const syncErrors = [];
      const syncHeaders = $Qrb(executionId);
      const resourceManifest = (this.collection ? manifest?.collections?.[this.collection]?.latest : manifest?.latest) ?? null;
      const userDataSyncConfiguration = merge2 ? await this.I(resourceManifest) : {};
      for (const synchroniser of synchronizers) {
        if (token.isCancellationRequested) {
          return [];
        }
        if (!this.r.isResourceEnabled(synchroniser.resource)) {
          return [];
        }
        try {
          if (merge2) {
            const preview = await synchroniser.preview(resourceManifest, userDataSyncConfiguration, syncHeaders);
            if (preview) {
              for (const resourcePreview of preview.resourcePreviews) {
                if ((resourcePreview.localChange !== 0 || resourcePreview.remoteChange !== 0) && resourcePreview.mergeState === "preview") {
                  await synchroniser.merge(resourcePreview.previewResource);
                }
              }
            }
          } else {
            await synchroniser.sync(resourceManifest, syncHeaders);
          }
        } catch (e) {
          const userDataSyncError = $Rrb.toUserDataSyncError(e);
          reportUserDataSyncError(userDataSyncError, executionId, this.w, this.y);
          if (canBailout(e)) {
            throw userDataSyncError;
          }
          this.z.error(e);
          this.z.error(`${synchroniser.resource}: ${$Kj(e)}`);
          syncErrors.push([synchroniser.resource, userDataSyncError]);
        }
      }
      return syncErrors;
    } finally {
      this.L();
    }
  }
  async apply(executionId, token) {
    const syncHeaders = $Qrb(executionId);
    for (const synchroniser of this.enabled) {
      if (token.isCancellationRequested) {
        return;
      }
      try {
        await synchroniser.apply(false, syncHeaders);
      } catch (e) {
        const userDataSyncError = $Rrb.toUserDataSyncError(e);
        reportUserDataSyncError(userDataSyncError, executionId, this.w, this.y);
        if (canBailout(e)) {
          throw userDataSyncError;
        }
        this.z.error(e);
        this.z.error(`${synchroniser.resource}: ${$Kj(e)}`);
      }
    }
  }
  async stop() {
    for (const synchroniser of this.enabled) {
      try {
        if (synchroniser.status !== "idle") {
          await synchroniser.stop();
        }
      } catch (e) {
        this.z.error(e);
      }
    }
  }
  async resetLocal() {
    for (const synchroniser of this.enabled) {
      try {
        await synchroniser.resetLocal();
      } catch (e) {
        this.z.error(`${synchroniser.resource}: ${$Kj(e)}`);
        this.z.error(e);
      }
    }
  }
  async I(manifest) {
    if (!this.profile.isDefault) {
      return {};
    }
    const local = this.D.getValue($Erb);
    const settingsSynchronizer = this.enabled.find((synchronizer) => synchronizer instanceof $2gc);
    if (settingsSynchronizer) {
      const remote = await settingsSynchronizer.getRemoteUserDataSyncConfiguration(manifest);
      return { ...local, ...remote };
    }
    return local;
  }
  J(status) {
    if (this.g !== status) {
      this.g = status;
      this.h.fire(status);
    }
  }
  L() {
    this.M();
    if (this.enabled.some(
      (s) => s.status === "hasConflicts"
      /* SyncStatus.HasConflicts */
    )) {
      return this.J(
        "hasConflicts"
        /* SyncStatus.HasConflicts */
      );
    }
    if (this.enabled.some(
      (s) => s.status === "syncing"
      /* SyncStatus.Syncing */
    )) {
      return this.J(
        "syncing"
        /* SyncStatus.Syncing */
      );
    }
    return this.J(
      "idle"
      /* SyncStatus.Idle */
    );
  }
  M() {
    const conflicts = this.enabled.filter(
      (s) => s.status === "hasConflicts"
      /* SyncStatus.HasConflicts */
    ).filter((s) => s.conflicts.conflicts.length > 0).map((s) => s.conflicts);
    if (!$Hb(this.m, conflicts, (a, b) => a.syncResource === b.syncResource && $Hb(a.conflicts, b.conflicts, (a2, b2) => $th(a2.previewResource, b2.previewResource)))) {
      this.m = conflicts;
      this.n.fire(conflicts);
    }
  }
  N(syncResource) {
    switch (syncResource) {
      case "settings":
        return 0;
      case "keybindings":
        return 1;
      case "snippets":
        return 2;
      case "tasks":
        return 3;
      case "globalState":
        return 4;
      case "extensions":
        return 5;
      case "profiles":
        return 6;
      case "workspaceState":
        return 7;
    }
  }
};
ProfileSynchronizer = __decorate([
  __param(2, $Wrb),
  __param(3, $Yi),
  __param(4, $Gp),
  __param(5, $Lrb),
  __param(6, $tm),
  __param(7, $2rb),
  __param(8, $7l),
  __param(9, $tj)
], ProfileSynchronizer);
function canBailout(e) {
  if (e instanceof $Rrb) {
    switch (e.code) {
      case "MethodNotFound":
      case "TooLarge":
      case "RemoteTooManyRequests":
      case "TooManyRequestsAndRetryAfter":
      case "LocalTooManyRequests":
      case "LocalTooManyProfiles":
      case "Gone":
      case "UpgradeRequired":
      case "IncompatibleRemoteContent":
      case "IncompatibleLocalContent":
        return true;
    }
  }
  return false;
}
function reportUserDataSyncError(userDataSyncError, executionId, userDataSyncStoreManagementService, telemetryService) {
  telemetryService.publicLog2("sync/error", {
    code: userDataSyncError.code,
    serverCode: userDataSyncError instanceof $Srb ? String(userDataSyncError.serverCode) : void 0,
    url: userDataSyncError instanceof $Srb ? userDataSyncError.url : void 0,
    resource: userDataSyncError.resource,
    executionId,
    service: userDataSyncStoreManagementService.userDataSyncStore.url.toString()
  });
}

// out-build/vs/platform/userDataSync/common/userDataSyncServiceIpc.js
function reviewSyncResource(syncResource, userDataProfilesService) {
  return { ...syncResource, profile: $8l(syncResource.profile, userDataProfilesService.profilesHome.scheme) };
}
function reviewSyncResourceHandle(syncResourceHandle) {
  return { created: syncResourceHandle.created, uri: URI.revive(syncResourceHandle.uri) };
}
var $imc = class {
  constructor(c, d, f) {
    this.c = c;
    this.d = d;
    this.f = f;
    this.a = /* @__PURE__ */ new Map();
    this.b = new $De();
  }
  listen(_, event) {
    switch (event) {
      case "onDidChangeStatus":
        return this.c.onDidChangeStatus;
      case "onDidChangeConflicts":
        return this.c.onDidChangeConflicts;
      case "onDidChangeLocal":
        return this.c.onDidChangeLocal;
      case "onDidChangeLastSyncTime":
        return this.c.onDidChangeLastSyncTime;
      case "onSyncErrors":
        return this.c.onSyncErrors;
      case "onDidResetLocal":
        return this.c.onDidResetLocal;
      case "onDidResetRemote":
        return this.c.onDidResetRemote;
      case "manualSync/onSynchronizeResources":
        return this.b.event;
    }
    throw new Error(`[UserDataSyncServiceChannel] Event not found: ${event}`);
  }
  async call(context, command, args) {
    try {
      const result = await this.g(context, command, args);
      return result;
    } catch (e) {
      this.f.error(e);
      throw e;
    }
  }
  async g(context, command, args) {
    switch (command) {
      case "_getInitialData":
        return Promise.resolve([this.c.status, this.c.conflicts, this.c.lastSyncTime]);
      case "reset":
        return this.c.reset();
      case "resetRemote":
        return this.c.resetRemote();
      case "resetLocal":
        return this.c.resetLocal();
      case "hasPreviouslySynced":
        return this.c.hasPreviouslySynced();
      case "hasLocalData":
        return this.c.hasLocalData();
      case "resolveContent":
        return this.c.resolveContent(URI.revive(args[0]));
      case "accept":
        return this.c.accept(reviewSyncResource(args[0], this.d), URI.revive(args[1]), args[2], args[3]);
      case "replace":
        return this.c.replace(reviewSyncResourceHandle(args[0]));
      case "cleanUpRemoteData":
        return this.c.cleanUpRemoteData();
      case "getRemoteActivityData":
        return this.c.saveRemoteActivityData(URI.revive(args[0]));
      case "extractActivityData":
        return this.c.extractActivityData(URI.revive(args[0]), URI.revive(args[1]));
      case "createManualSyncTask":
        return this.i();
    }
    if (command.startsWith("manualSync/")) {
      const manualSyncTaskCommand = command.substring("manualSync/".length);
      const manualSyncTaskId = args[0];
      const manualSyncTask = this.h(manualSyncTaskId);
      args = args.slice(1);
      switch (manualSyncTaskCommand) {
        case "merge":
          return manualSyncTask.merge();
        case "apply":
          return manualSyncTask.apply().then(() => this.a.delete(this.j(manualSyncTask.id)));
        case "stop":
          return manualSyncTask.stop().finally(() => this.a.delete(this.j(manualSyncTask.id)));
      }
    }
    throw new Error("Invalid call");
  }
  h(manualSyncTaskId) {
    const manualSyncTask = this.a.get(this.j(manualSyncTaskId));
    if (!manualSyncTask) {
      throw new Error(`Manual sync taks not found: ${manualSyncTaskId}`);
    }
    return manualSyncTask;
  }
  async i() {
    const manualSyncTask = await this.c.createManualSyncTask();
    this.a.set(this.j(manualSyncTask.id), manualSyncTask);
    return manualSyncTask.id;
  }
  j(manualSyncTaskId) {
    return `manualSyncTask-${manualSyncTaskId}`;
  }
};
var $jmc = class $jmc2 extends $0c {
  get status() {
    return this.b;
  }
  get onDidChangeLocal() {
    return this.a.listen("onDidChangeLocal");
  }
  get conflicts() {
    return this.f;
  }
  get lastSyncTime() {
    return this.h;
  }
  get onDidResetLocal() {
    return this.a.listen("onDidResetLocal");
  }
  get onDidResetRemote() {
    return this.a.listen("onDidResetRemote");
  }
  constructor(userDataSyncChannel, n) {
    super();
    this.n = n;
    this.b = "uninitialized";
    this.c = this.B(new $De());
    this.onDidChangeStatus = this.c.event;
    this.f = [];
    this.g = this.B(new $De());
    this.onDidChangeConflicts = this.g.event;
    this.h = void 0;
    this.j = this.B(new $De());
    this.onDidChangeLastSyncTime = this.j.event;
    this.m = this.B(new $De());
    this.onSyncErrors = this.m.event;
    this.a = {
      call(command, arg, cancellationToken) {
        return userDataSyncChannel.call(command, arg, cancellationToken).then(null, (error) => {
          throw $Rrb.toUserDataSyncError(error);
        });
      },
      listen(event, arg) {
        return userDataSyncChannel.listen(event, arg);
      }
    };
    this.a.call("_getInitialData").then(([status, conflicts, lastSyncTime]) => {
      this.s(status);
      this.t(conflicts);
      if (lastSyncTime) {
        this.u(lastSyncTime);
      }
      this.B(this.a.listen("onDidChangeStatus")((status2) => this.s(status2)));
      this.B(this.a.listen("onDidChangeLastSyncTime")((lastSyncTime2) => this.u(lastSyncTime2)));
    });
    this.B(this.a.listen("onDidChangeConflicts")((conflicts) => this.t(conflicts)));
    this.B(this.a.listen("onSyncErrors")((errors) => this.m.fire(errors.map((syncError) => ({ ...syncError, error: $Rrb.toUserDataSyncError(syncError.error) })))));
  }
  createSyncTask() {
    throw new Error("not supported");
  }
  async createManualSyncTask() {
    const id2 = await this.a.call("createManualSyncTask");
    const that = this;
    const manualSyncTaskChannelClient = new ManualSyncTaskChannelClient(id2, {
      async call(command, arg, cancellationToken) {
        return that.a.call(`manualSync/${command}`, [id2, ...Array.isArray(arg) ? arg : [arg]], cancellationToken);
      },
      listen() {
        throw new Error("not supported");
      }
    });
    return manualSyncTaskChannelClient;
  }
  reset() {
    return this.a.call("reset");
  }
  resetRemote() {
    return this.a.call("resetRemote");
  }
  resetLocal() {
    return this.a.call("resetLocal");
  }
  hasPreviouslySynced() {
    return this.a.call("hasPreviouslySynced");
  }
  hasLocalData() {
    return this.a.call("hasLocalData");
  }
  accept(syncResource, resource, content, apply) {
    return this.a.call("accept", [syncResource, resource, content, apply]);
  }
  resolveContent(resource) {
    return this.a.call("resolveContent", [resource]);
  }
  cleanUpRemoteData() {
    return this.a.call("cleanUpRemoteData");
  }
  replace(syncResourceHandle) {
    return this.a.call("replace", [syncResourceHandle]);
  }
  saveRemoteActivityData(location) {
    return this.a.call("getRemoteActivityData", [location]);
  }
  extractActivityData(activityDataResource, location) {
    return this.a.call("extractActivityData", [activityDataResource, location]);
  }
  async s(status) {
    this.b = status;
    this.c.fire(status);
  }
  async t(conflicts) {
    this.f = conflicts.map((syncConflict) => ({
      syncResource: syncConflict.syncResource,
      profile: $8l(syncConflict.profile, this.n.profilesHome.scheme),
      conflicts: syncConflict.conflicts.map((r) => ({
        ...r,
        baseResource: URI.revive(r.baseResource),
        localResource: URI.revive(r.localResource),
        remoteResource: URI.revive(r.remoteResource),
        previewResource: URI.revive(r.previewResource)
      }))
    }));
    this.g.fire(this.f);
  }
  u(lastSyncTime) {
    if (this.h !== lastSyncTime) {
      this.h = lastSyncTime;
      this.j.fire(lastSyncTime);
    }
  }
};
$jmc = __decorate([
  __param(1, $7l)
], $jmc);
var ManualSyncTaskChannelClient = class extends $0c {
  constructor(id2, a) {
    super();
    this.id = id2;
    this.a = a;
  }
  async merge() {
    return this.a.call("merge");
  }
  async apply() {
    return this.a.call("apply");
  }
  stop() {
    return this.a.call("stop");
  }
  dispose() {
    this.a.call("dispose");
    super.dispose();
  }
};

// out-build/vs/platform/userDataProfile/node/userDataProfileStorageService.js
var $kmc = class $kmc2 extends $iSb {
  constructor(mainProcessService, userDataProfilesService, storageService, logService) {
    super(true, mainProcessService, userDataProfilesService, storageService, logService);
  }
};
$kmc = __decorate([
  __param(0, $HOb),
  __param(1, $7l),
  __param(2, $Dq),
  __param(3, $uk)
], $kmc);

// 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/sign/common/sign.js
var $gm = "signService";
var $hm = $Zi($gm);

// 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/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, os4, osRelease) {
  if (os4 === 1) {
    return false;
  }
  if (os4 === 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, protocol) {
    this.z(remoteHost, remotePort, Promise.resolve({
      tunnelRemoteHost: remoteHost,
      tunnelRemotePort: remotePort,
      localAddress,
      privacy,
      protocol,
      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, protocol) {
    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, protocol);
    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, protocol) {
    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 };
    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 os from "os";

// out-build/vs/base/node/ports.js
import * as net from "net";
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, resolve) {
    if (!resolved) {
      resolved = true;
      server.removeAllListeners();
      server.close();
      if (timeoutHandle) {
        clearTimeout(timeoutHandle);
      }
      resolve(port);
    }
  }
  return new Promise((resolve) => {
    timeoutHandle = setTimeout(() => {
      doResolve(0, resolve);
    }, timeout);
    server.on("listening", () => {
      doResolve(startPort, resolve);
    });
    server.on("error", (err) => {
      if (err && (err.code === "EADDRINUSE" || err.code === "EACCES") && countTried < giveUpAfter) {
        startPort++;
        countTried++;
        server.listen(startPort, hostname3);
      } else {
        doResolve(0, resolve);
      }
    });
    server.on("close", () => {
      doResolve(0, resolve);
    });
    server.listen(startPort, hostname3);
  });
}

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

// 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, type2, 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: type2, buff: copiedData });
    } else {
      SocketDiagnostics2.records.push({ timestamp: Date.now(), id: id2, label: socketDebugLabel, type: type2, 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(type2, id2, ack, data) {
    this.type = type2;
    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 $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 now = Date.now();
    for (let i = 0; i < _LoadEstimator.a; i++) {
      this.c[i] = now - 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 now = Date.now();
    const historyLimit = (1 + _LoadEstimator.a) * 1e3;
    let score = 0;
    for (let i = 0; i < _LoadEstimator.a; i++) {
      if (now - 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 now = Date.now();
            if (now - this.n > 1e4) {
              this.n = now;
              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(type2, data) {
    SocketDiagnostics.traceSocketEvent(this.socket, this.debugLabel, type2, 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((resolve, reject) => {
      if (this.socket.bufferSize === 0) {
        this.traceSocketEvent(
          "nodeDrainEnd"
          /* SocketDiagnosticsEventType.NodeDrainEnd */
        );
        resolve();
        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 */
        );
        resolve();
      };
      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(Constants2) {
  Constants2[Constants2["MinHeaderByteSize"] = 2] = "MinHeaderByteSize";
  Constants2[Constants2["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"];

// 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, code = RemoteAuthorityResolverErrorCode.Unknown, detail) {
    super(message);
    this._message = message;
    this._code = code;
    this._detail = detail;
    this.isHandled = code === 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(protocol, timeoutCancellationToken) {
  const result = new PromiseWithTimeout(timeoutCancellationToken);
  result.registerDisposable(protocol.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, path2, 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, path2, 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 protocol;
  let ownsProtocol;
  if (options.reconnectionProtocol) {
    options.reconnectionProtocol.beginAcceptReconnection(socket, null);
    protocol = options.reconnectionProtocol;
    ownsProtocol = false;
  } else {
    protocol = 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
  };
  protocol.sendControl($7e.fromString(JSON.stringify(authRequest)));
  try {
    const msg = await readOneControlMessage(protocol, 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.`);
    protocol.sendControl($7e.fromString(JSON.stringify(connTypeRequest)));
    return { protocol, 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(protocol);
    }
    throw error;
  }
}
async function doConnectRemoteAgentTunnel(options, startParams, timeoutCancellationToken) {
  const startTime = Date.now();
  const logPrefix = connectLogPrefix(
    options,
    3
    /* ConnectionType.Tunnel */
  );
  const { protocol } = await connectToRemoteExtensionHostAgent(options, 3, startParams, timeoutCancellationToken);
  options.logService.trace(`${logPrefix} 6/6. handshake finished, connection is up and running after ${logElapsed(startTime)}!`);
  return protocol;
}
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 protocol = await doConnectRemoteAgentTunnel(simpleOptions, { host: tunnelRemoteHost, port: tunnelRemotePort }, CancellationToken.None);
  return protocol;
}
function sleep(seconds) {
  return $Mh((token) => {
    return new Promise((resolve, reject) => {
      const timeout = setTimeout(resolve, seconds * 1e3);
      token.onCancellationRequested(() => {
        clearTimeout(timeout);
        resolve();
      });
    });
  });
}
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, protocol, w) {
    super();
    this.t = t;
    this.u = u;
    this.reconnectionToken = reconnectionToken;
    this.protocol = protocol;
    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(protocol.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(protocol.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(protocol) {
  try {
    protocol.acceptDisconnect();
    const socket = protocol.getSocket();
    protocol.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");
var $fm = class {
  constructor() {
    this.a = {};
  }
  register(type2, factory) {
    this.a[type2] ??= [];
    this.a[type2].push(factory);
    return $8c(() => {
      const idx = this.a[type2]?.indexOf(factory);
      if (typeof idx === "number" && idx >= 0) {
        this.a[type2]?.splice(idx, 1);
      }
    });
  }
  b(messagePassing) {
    const factories = this.a[messagePassing.type] || [];
    return factories.find((factory) => factory.supports(messagePassing));
  }
  connect(connectTo, path2, query, debugLabel) {
    const socketFactory = this.b(connectTo);
    if (!socketFactory) {
      throw new Error(`No socket factory found for ${connectTo}`);
    }
    return socketFactory.connect(connectTo, path2, query, debugLabel);
  }
};

// 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 protocol = await $km(this.a, tunnelRemoteHost, this.tunnelRemotePort);
    const remoteSocket = protocol.getSocket();
    const dataChunk = protocol.readEntireBuffer();
    protocol.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, os.release());
  }
  F(addressOrTunnelProvider, remoteHost, remotePort, localHost, localPort, elevateIfNeeded, privacy, protocol) {
    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, protocol);
    } 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, protocol) {
    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, protocol);
  }
};
$Ulc = __decorate([
  __param(0, $em),
  __param(1, $uk),
  __param(2, $Nk),
  __param(3, $hm),
  __param(4, $tj)
], $Ulc);

// out-build/vs/platform/remote/common/sharedProcessTunnelService.js
var $lmc = $Zi("sharedProcessTunnelService");
var $mmc = "sharedProcessTunnel";

// out-build/vs/platform/tunnel/node/sharedProcessTunnelService.js
var $nmc_1;
var TunnelData = class extends $0c {
  constructor() {
    super();
    this.a = null;
    this.b = null;
  }
  async getAddress() {
    if (this.a) {
      return this.a;
    }
    if (!this.b) {
      this.b = new $ki();
    }
    return this.b.p;
  }
  setAddress(address) {
    this.a = address;
    if (this.b) {
      this.b.complete(address);
      this.b = null;
    }
  }
  setTunnel(tunnel) {
    this.B(tunnel);
  }
};
var $nmc = class $nmc2 extends $0c {
  static {
    $nmc_1 = this;
  }
  static {
    this.a = 0;
  }
  constructor(f, g) {
    super();
    this.f = f;
    this.g = g;
    this.b = /* @__PURE__ */ new Map();
    this.c = /* @__PURE__ */ new Set();
  }
  dispose() {
    super.dispose();
    this.b.forEach((tunnel) => tunnel.dispose());
  }
  async createTunnel() {
    const id2 = String(++$nmc_1.a);
    return { id: id2 };
  }
  async startTunnel(authority, id2, tunnelRemoteHost, tunnelRemotePort, tunnelLocalHost, tunnelLocalPort, elevateIfNeeded) {
    const tunnelData = new TunnelData();
    const tunnel = await Promise.resolve(this.f.openTunnel(authority, tunnelData, tunnelRemoteHost, tunnelRemotePort, tunnelLocalHost, tunnelLocalPort, elevateIfNeeded));
    if (!tunnel || typeof tunnel === "string") {
      this.g.info(`[SharedProcessTunnelService] Could not create a tunnel to ${tunnelRemoteHost}:${tunnelRemotePort} (remote).`);
      tunnelData.dispose();
      throw new Error(`Could not create tunnel`);
    }
    if (this.c.has(id2)) {
      this.c.delete(id2);
      tunnelData.dispose();
      await tunnel.dispose();
      throw $gb();
    }
    tunnelData.setTunnel(tunnel);
    this.b.set(id2, tunnelData);
    this.g.info(`[SharedProcessTunnelService] Created tunnel ${id2}: ${tunnel.localAddress} (local) to ${tunnelRemoteHost}:${tunnelRemotePort} (remote).`);
    const result = {
      tunnelLocalPort: tunnel.tunnelLocalPort,
      localAddress: tunnel.localAddress
    };
    return result;
  }
  async setAddress(id2, address) {
    const tunnel = this.b.get(id2);
    if (!tunnel) {
      return;
    }
    tunnel.setAddress(address);
  }
  async destroyTunnel(id2) {
    const tunnel = this.b.get(id2);
    if (tunnel) {
      this.g.info(`[SharedProcessTunnelService] Disposing tunnel ${id2}.`);
      this.b.delete(id2);
      await tunnel.dispose();
      return;
    }
    this.c.add(id2);
  }
};
$nmc = $nmc_1 = __decorate([
  __param(0, $bx),
  __param(1, $uk)
], $nmc);

// 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/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/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/platform/files/common/diskFileSystemProviderClient.js
var $rS = "localFilesystem";
var $sS = class extends $0c {
  constructor(a, b) {
    super();
    this.a = a;
    this.b = b;
    this.onDidChangeCapabilities = Event.None;
    this.f = this.B(new $De());
    this.onDidChangeFile = this.f.event;
    this.g = this.B(new $De());
    this.onDidWatchError = this.g.event;
    this.h = $jh();
    this.j();
  }
  get capabilities() {
    if (!this.c) {
      this.c = 2 | 4 | 16 | 8 | 8192 | 16384 | 32768 | 65536 | 131072;
      if (this.b.pathCaseSensitive) {
        this.c |= 1024;
      }
      if (this.b.trash) {
        this.c |= 4096;
      }
    }
    return this.c;
  }
  //#endregion
  //#region File Metadata Resolving
  stat(resource) {
    return this.a.call("stat", [resource]);
  }
  readdir(resource) {
    return this.a.call("readdir", [resource]);
  }
  //#endregion
  //#region File Reading/Writing
  async readFile(resource, opts) {
    const { buffer } = await this.a.call("readFile", [resource, opts]);
    return buffer;
  }
  readFileStream(resource, opts, token) {
    const stream = $Ue((data) => $7e.concat(data.map((data2) => $7e.wrap(data2))).buffer);
    const disposables = new $9c();
    disposables.add(this.a.listen("readFileStream", [resource, opts])((dataOrErrorOrEnd) => {
      if (dataOrErrorOrEnd instanceof $7e) {
        stream.write(dataOrErrorOrEnd.buffer);
      } else {
        if (dataOrErrorOrEnd === "end") {
          stream.end();
        } else {
          let error;
          if (dataOrErrorOrEnd instanceof Error) {
            error = dataOrErrorOrEnd;
          } else {
            const errorCandidate = dataOrErrorOrEnd;
            error = $Hl(errorCandidate.message ?? $Kj(errorCandidate), errorCandidate.code ?? FileSystemProviderErrorCode.Unknown);
          }
          stream.error(error);
          stream.end();
        }
        disposables.dispose();
      }
    }));
    disposables.add(token.onCancellationRequested(() => {
      stream.error($gb());
      stream.end();
      disposables.dispose();
    }));
    return stream;
  }
  writeFile(resource, content, opts) {
    return this.a.call("writeFile", [resource, $7e.wrap(content), opts]);
  }
  open(resource, opts) {
    return this.a.call("open", [resource, opts]);
  }
  close(fd) {
    return this.a.call("close", [fd]);
  }
  async read(fd, pos, data, offset, length) {
    const [bytes, bytesRead] = await this.a.call("read", [fd, pos, length]);
    data.set(bytes.buffer.slice(0, bytesRead), offset);
    return bytesRead;
  }
  write(fd, pos, data, offset, length) {
    return this.a.call("write", [fd, pos, $7e.wrap(data), offset, length]);
  }
  //#endregion
  //#region Move/Copy/Delete/Create Folder
  mkdir(resource) {
    return this.a.call("mkdir", [resource]);
  }
  delete(resource, opts) {
    return this.a.call("delete", [resource, opts]);
  }
  rename(resource, target, opts) {
    return this.a.call("rename", [resource, target, opts]);
  }
  copy(resource, target, opts) {
    return this.a.call("copy", [resource, target, opts]);
  }
  //#endregion
  //#region Clone File
  cloneFile(resource, target) {
    return this.a.call("cloneFile", [resource, target]);
  }
  j() {
    this.B(this.a.listen("fileChange", [this.h])((eventsOrError) => {
      if (Array.isArray(eventsOrError)) {
        const events = eventsOrError;
        this.f.fire($sr(events));
      } else {
        const error = eventsOrError;
        this.g.fire(error);
      }
    }));
  }
  watch(resource, opts) {
    const req = $jh();
    this.a.call("watch", [this.h, req, resource, opts]);
    return $8c(() => this.a.call("unwatch", [this.h, req]));
  }
};

// out-build/vs/platform/profiling/node/profilingService.js
var $omc = class {
  constructor() {
    this.a = /* @__PURE__ */ new Map();
  }
  async startProfiling(options) {
    const prof = await import("v8-inspect-profiler");
    const session = await prof.startProfiling({ host: options.host, port: options.port, checkForPaused: true });
    const id2 = $jh();
    this.a.set(id2, session);
    return id2;
  }
  async stopProfiling(sessionId) {
    const session = this.a.get(sessionId);
    if (!session) {
      throw new Error(`UNKNOWN session '${sessionId}'`);
    }
    const result = await session.stop();
    this.a.delete(sessionId);
    return result.profile;
  }
};

// out-build/vs/platform/profiling/common/profiling.js
var $GH = $Zi("IV8InspectProfilingService");
var Utils;
(function(Utils2) {
  function isValidProfile(profile) {
    return Boolean(profile.samples && profile.timeDeltas);
  }
  Utils2.isValidProfile = isValidProfile;
  function rewriteAbsolutePaths(profile, replace = "noAbsolutePaths") {
    for (const node of profile.nodes) {
      if (node.callFrame && node.callFrame.url) {
        if ($uc(node.callFrame.url) || /^\w[\w\d+.-]*:\/\/\/?/.test(node.callFrame.url)) {
          node.callFrame.url = $vc(replace, $zc(node.callFrame.url));
        }
      }
    }
    return profile;
  }
  Utils2.rewriteAbsolutePaths = rewriteAbsolutePaths;
})(Utils || (Utils = {}));

// 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/policy/common/policyIpc.js
var $llc = class extends $Po {
  constructor(policiesData, a) {
    super();
    this.a = a;
    for (const name in policiesData) {
      const { definition, value } = policiesData[name];
      this.f[name] = definition;
      if (value !== void 0) {
        this.g.set(name, value);
      }
    }
    this.a.listen("onDidChange")((policies) => {
      for (const name in policies) {
        const value = policies[name];
        if (value === null) {
          this.g.delete(name);
        } else {
          this.g.set(name, value);
        }
      }
      this.h.fire(Object.keys(policies));
    });
  }
  async j(policyDefinitions) {
    const result = await this.a.call("updatePolicyDefinitions", policyDefinitions);
    for (const name in result) {
      this.g.set(name, result[name]);
    }
  }
};

// out-build/vs/platform/userDataProfile/common/userDataProfileIpc.js
var $QS = class extends $0c {
  get defaultProfile() {
    return this.profiles[0];
  }
  get profiles() {
    return this.a;
  }
  constructor(profiles, profilesHome, f) {
    super();
    this.profilesHome = profilesHome;
    this.f = f;
    this.a = [];
    this.b = this.B(new $De());
    this.onDidChangeProfiles = this.b.event;
    this.c = true;
    this.a = profiles.map((profile) => $8l(profile, this.profilesHome.scheme));
    this.B(this.f.listen("onDidChangeProfiles")((e) => {
      const added = e.added.map((profile) => $8l(profile, this.profilesHome.scheme));
      const removed = e.removed.map((profile) => $8l(profile, this.profilesHome.scheme));
      const updated = e.updated.map((profile) => $8l(profile, this.profilesHome.scheme));
      this.a = e.all.map((profile) => $8l(profile, this.profilesHome.scheme));
      this.b.fire({ added, removed, updated, all: this.profiles });
    }));
    this.onDidResetWorkspaces = this.f.listen("onDidResetWorkspaces");
  }
  setEnablement(enabled) {
    this.c = enabled;
  }
  isEnabled() {
    return this.c;
  }
  async createNamedProfile(name, options, workspaceIdentifier) {
    const result = await this.f.call("createNamedProfile", [name, options, workspaceIdentifier]);
    return $8l(result, this.profilesHome.scheme);
  }
  async createProfile(id2, name, options, workspaceIdentifier) {
    const result = await this.f.call("createProfile", [id2, name, options, workspaceIdentifier]);
    return $8l(result, this.profilesHome.scheme);
  }
  async createTransientProfile(workspaceIdentifier) {
    const result = await this.f.call("createTransientProfile", [workspaceIdentifier]);
    return $8l(result, this.profilesHome.scheme);
  }
  async setProfileForWorkspace(workspaceIdentifier, profile) {
    await this.f.call("setProfileForWorkspace", [workspaceIdentifier, profile]);
  }
  removeProfile(profile) {
    return this.f.call("removeProfile", [profile]);
  }
  async updateProfile(profile, updateOptions) {
    const result = await this.f.call("updateProfile", [profile, updateOptions]);
    return $8l(result, this.profilesHome.scheme);
  }
  resetWorkspaces() {
    return this.f.call("resetWorkspaces");
  }
  cleanUp() {
    return this.f.call("cleanUp");
  }
  cleanUpTransientProfiles() {
    return this.f.call("cleanUpTransientProfiles");
  }
};

// out-build/vs/platform/telemetry/node/1dsAppender.js
import * as https from "https";

// out-build/vs/platform/telemetry/common/1dsAppender.js
var endpointUrl = "https://mobile.events.data.microsoft.com/OneCollector/1.0";
var endpointHealthUrl = "https://mobile.events.data.microsoft.com/ping";
async function getClient(instrumentationKey, addInternalFlag, xhrOverride) {
  const oneDs = $r ? await $Oq("@microsoft/1ds-core-js", "bundle/ms.core.min.js") : await import("@microsoft/1ds-core-js");
  const postPlugin = $r ? await $Oq("@microsoft/1ds-post-js", "bundle/ms.post.min.js") : await import("@microsoft/1ds-post-js");
  const appInsightsCore = new oneDs.AppInsightsCore();
  const collectorChannelPlugin = new postPlugin.PostChannel();
  const coreConfig = {
    instrumentationKey,
    endpointUrl,
    loggingLevelTelemetry: 0,
    loggingLevelConsole: 0,
    disableCookiesUsage: true,
    disableDbgExt: true,
    disableInstrumentationKeyValidation: true,
    channels: [[
      collectorChannelPlugin
    ]]
  };
  if (xhrOverride) {
    coreConfig.extensionConfig = {};
    const channelConfig = {
      alwaysUseXhrOverride: true,
      ignoreMc1Ms0CookieProcessing: true,
      httpXHROverride: xhrOverride
    };
    coreConfig.extensionConfig[collectorChannelPlugin.identifier] = channelConfig;
  }
  appInsightsCore.initialize(coreConfig, []);
  appInsightsCore.addTelemetryInitializer((envelope) => {
    envelope["ext"] = envelope["ext"] ?? {};
    envelope["ext"]["web"] = envelope["ext"]["web"] ?? {};
    envelope["ext"]["web"]["consentDetails"] = '{"GPC_DataSharingOptIn":false}';
    if (addInternalFlag) {
      envelope["ext"]["utc"] = envelope["ext"]["utc"] ?? {};
      envelope["ext"]["utc"]["flags"] = 8462029;
    }
  });
  return appInsightsCore;
}
var $wS = class {
  constructor(e, f, g, iKeyOrClientFactory, h) {
    this.e = e;
    this.f = f;
    this.g = g;
    this.h = h;
    this.c = endpointUrl;
    this.d = endpointHealthUrl;
    if (!this.g) {
      this.g = {};
    }
    if (typeof iKeyOrClientFactory === "function") {
      this.a = iKeyOrClientFactory();
    } else {
      this.a = iKeyOrClientFactory;
    }
    this.b = null;
  }
  i(callback) {
    if (!this.a) {
      return;
    }
    if (typeof this.a !== "string") {
      callback(this.a);
      return;
    }
    if (!this.b) {
      this.b = getClient(this.a, this.e, this.h);
    }
    this.b.then((aiClient) => {
      callback(aiClient);
    }, (err) => {
      $ab(err);
      console.error(err);
    });
  }
  log(eventName, data) {
    if (!this.a) {
      return;
    }
    data = $Co(data, this.g);
    data = $3p(data);
    const name = this.f + "/" + eventName;
    try {
      this.i((aiClient) => {
        aiClient.pluginVersionString = data?.properties.version ?? "Unknown";
        aiClient.track({
          name,
          baseData: { name, properties: data?.properties, measurements: data?.measurements }
        });
      });
    } catch {
    }
  }
  flush() {
    if (this.a) {
      return new Promise((resolve) => {
        this.i((aiClient) => {
          aiClient.unload(true, () => {
            this.a = void 0;
            resolve(void 0);
          });
        });
      });
    }
    return Promise.resolve(void 0);
  }
};

// out-build/vs/platform/telemetry/node/1dsAppender.js
async function makeTelemetryRequest(options, requestService) {
  const response = await requestService.request(options, CancellationToken.None);
  const responseData = (await $gf(response.stream)).toString();
  const statusCode = response.res.statusCode ?? 200;
  const headers = response.res.headers;
  return {
    headers,
    statusCode,
    responseData
  };
}
async function makeLegacyTelemetryRequest(options) {
  const httpsOptions = {
    method: options.type,
    headers: options.headers
  };
  const responsePromise = new Promise((resolve, reject) => {
    const req = https.request(options.url ?? "", httpsOptions, (res) => {
      res.on("data", function(responseData) {
        resolve({
          headers: res.headers,
          statusCode: res.statusCode ?? 200,
          responseData: responseData.toString()
        });
      });
      res.on("error", function(err) {
        reject(err);
      });
    });
    req.write(options.data, (err) => {
      if (err) {
        reject(err);
      }
    });
    req.end();
  });
  return responsePromise;
}
async function sendPostAsync(requestService, payload, oncomplete) {
  const telemetryRequestData = typeof payload.data === "string" ? payload.data : new TextDecoder().decode(payload.data);
  const requestOptions = {
    type: "POST",
    headers: {
      ...payload.headers,
      "Content-Type": "application/json",
      "Content-Length": Buffer.byteLength(payload.data).toString()
    },
    url: payload.urlString,
    data: telemetryRequestData
  };
  try {
    const responseData = requestService ? await makeTelemetryRequest(requestOptions, requestService) : await makeLegacyTelemetryRequest(requestOptions);
    oncomplete(responseData.statusCode, responseData.headers, responseData.responseData);
  } catch {
    oncomplete(0, {});
  }
}
var $xS = class extends $wS {
  constructor(requestService, isInternalTelemetry, eventPrefix, defaultData, iKeyOrClientFactory) {
    const customHttpXHROverride = {
      sendPOST: (payload, oncomplete) => {
        sendPostAsync(requestService, payload, oncomplete);
      }
    };
    super(isInternalTelemetry, eventPrefix, defaultData, iKeyOrClientFactory, customHttpXHROverride);
  }
};

// out-build/vs/code/electron-utility/sharedProcess/contrib/userDataProfilesCleaner.js
var $pmc = class $pmc2 extends $0c {
  constructor(userDataProfilesService) {
    super();
    const scheduler = this.B(new $_h(
      () => {
        userDataProfilesService.cleanUp();
      },
      10 * 1e3
      /* after 10s */
    ));
    scheduler.schedule();
  }
};
$pmc = __decorate([
  __param(0, $7l)
], $pmc);

// out-build/vs/platform/remoteTunnel/common/remoteTunnel.js
var $qmc = $Zi("IRemoteTunnelService");
var $rmc = { active: false };
var TunnelStates;
(function(TunnelStates2) {
  TunnelStates2.disconnected = (onTokenFailed) => ({ type: "disconnected", onTokenFailed });
  TunnelStates2.connected = (info, serviceInstallFailed) => ({ type: "connected", info, serviceInstallFailed });
  TunnelStates2.connecting = (progress) => ({ type: "connecting", progress });
  TunnelStates2.uninitialized = { type: "uninitialized" };
})(TunnelStates || (TunnelStates = {}));
var $smc = "remote.tunnels.access";
var $tmc = $smc + ".hostNameOverride";
var $umc = $smc + ".preventSleep";
var $vmc = "remoteTunnelService";
var $wmc = localize(2058, null);

// out-build/vs/platform/userDataSync/common/userDataSyncResourceProvider.js
var $Ajc_1;
var $Ajc = class $Ajc2 {
  static {
    $Ajc_1 = this;
  }
  static {
    this.a = "not-existing-resource";
  }
  static {
    this.b = "remote-backup";
  }
  static {
    this.c = "local-backup";
  }
  constructor(e, f, g, uriIdentityService, h, i, j, k, l, n) {
    this.e = e;
    this.f = f;
    this.g = g;
    this.h = h;
    this.i = i;
    this.j = j;
    this.k = k;
    this.l = l;
    this.n = n;
    this.d = uriIdentityService.extUri;
  }
  async getRemoteSyncedProfiles() {
    const userData = await this.e.readResource("profiles", null, void 0);
    if (userData.content) {
      const syncData = this.L(
        userData.content,
        "profiles"
        /* SyncResource.Profiles */
      );
      return $Uic(syncData);
    }
    return [];
  }
  async getLocalSyncedProfiles(location) {
    const refs = await this.f.getAllResourceRefs("profiles", void 0, location);
    if (refs.length) {
      const content = await this.f.resolveResourceContent("profiles", refs[0].ref, void 0, location);
      if (content) {
        const syncData = this.L(
          content,
          "profiles"
          /* SyncResource.Profiles */
        );
        return $Uic(syncData);
      }
    }
    return [];
  }
  async getLocalSyncedMachines(location) {
    const refs = await this.f.getAllResourceRefs("machines", void 0, location);
    if (refs.length) {
      const content = await this.f.resolveResourceContent("machines", refs[0].ref, void 0, location);
      if (content) {
        const machinesData = JSON.parse(content);
        return machinesData.machines.map((m) => ({ ...m, isCurrent: false }));
      }
    }
    return [];
  }
  async getRemoteSyncResourceHandles(syncResource, profile) {
    const handles = await this.e.getAllResourceRefs(syncResource, profile?.collection);
    return handles.map(({ created, ref }) => ({
      created,
      uri: this.J({
        remote: true,
        syncResource,
        profile: profile?.id ?? this.k.defaultProfile.id,
        location: void 0,
        collection: profile?.collection,
        ref,
        node: void 0
      })
    }));
  }
  async getLocalSyncResourceHandles(syncResource, profile, location) {
    const handles = await this.f.getAllResourceRefs(syncResource, profile?.collection, location);
    return handles.map(({ created, ref }) => ({
      created,
      uri: this.J({
        remote: false,
        syncResource,
        profile: profile?.id ?? this.k.defaultProfile.id,
        collection: profile?.collection,
        ref,
        node: void 0,
        location
      })
    }));
  }
  resolveUserDataSyncResource({ uri }) {
    const resolved = this.K(uri);
    const profile = resolved ? this.k.profiles.find((p) => p.id === resolved.profile) : void 0;
    return resolved && profile ? { profile, syncResource: resolved?.syncResource } : void 0;
  }
  async getAssociatedResources({ uri }) {
    const resolved = this.K(uri);
    if (!resolved) {
      return [];
    }
    const profile = this.k.profiles.find((p) => p.id === resolved.profile);
    switch (resolved.syncResource) {
      case "settings":
        return this.s(uri, profile);
      case "keybindings":
        return this.u(uri, profile);
      case "tasks":
        return this.w(uri, profile);
      case "snippets":
        return this.y(uri, profile);
      case "globalState":
        return this.D(uri, profile);
      case "extensions":
        return this.A(uri, profile);
      case "profiles":
        return this.G(uri, profile);
      case "workspaceState":
        return [];
    }
  }
  async getMachineId({ uri }) {
    const resolved = this.K(uri);
    if (!resolved) {
      return void 0;
    }
    if (resolved.remote) {
      if (resolved.ref) {
        const { content } = await this.M(resolved.syncResource, resolved.ref, resolved.collection);
        if (content) {
          const syncData = this.L(content, resolved.syncResource);
          return syncData?.machineId;
        }
      }
      return void 0;
    }
    if (resolved.location) {
      if (resolved.ref) {
        const content = await this.f.resolveResourceContent(resolved.syncResource, resolved.ref, resolved.collection, resolved.location);
        if (content) {
          const syncData = this.L(content, resolved.syncResource);
          return syncData?.machineId;
        }
      }
      return void 0;
    }
    return $Jq(this.h, this.j, this.i);
  }
  async resolveContent(uri) {
    const resolved = this.K(uri);
    if (!resolved) {
      return null;
    }
    if (resolved.node === $Ajc_1.a) {
      return null;
    }
    if (resolved.ref) {
      const content = await this.o(resolved.remote, resolved.syncResource, resolved.collection, resolved.ref, resolved.location);
      if (resolved.node && content) {
        return this.q(resolved.syncResource, content, resolved.node);
      }
      return content;
    }
    if (!resolved.remote && !resolved.node) {
      return this.r(resolved.syncResource, resolved.profile);
    }
    return null;
  }
  async o(remote, syncResource, collection, ref, location) {
    if (remote) {
      const { content } = await this.M(syncResource, ref, collection);
      return content;
    }
    return this.f.resolveResourceContent(syncResource, ref, collection, location);
  }
  q(syncResource, content, node) {
    const syncData = this.L(content, syncResource);
    switch (syncResource) {
      case "settings":
        return this.t(syncData, node);
      case "keybindings":
        return this.v(syncData, node);
      case "tasks":
        return this.x(syncData, node);
      case "snippets":
        return this.z(syncData, node);
      case "globalState":
        return this.E(syncData, node);
      case "extensions":
        return this.B(syncData, node);
      case "profiles":
        return this.H(syncData, node);
      case "workspaceState":
        return null;
    }
  }
  async r(syncResource, profileId) {
    const profile = this.k.profiles.find((p) => p.id === profileId);
    if (!profile) {
      return null;
    }
    switch (syncResource) {
      case "globalState":
        return this.F(profile);
      case "extensions":
        return this.C(profile);
      case "profiles":
        return this.I(profile);
      case "settings":
        return null;
      case "keybindings":
        return null;
      case "tasks":
        return null;
      case "snippets":
        return null;
      case "workspaceState":
        return null;
    }
  }
  s(uri, profile) {
    const resource = this.d.joinPath(uri, "settings.json");
    const comparableResource = profile ? profile.settingsResource : this.d.joinPath(uri, $Ajc_1.a);
    return [{ resource, comparableResource }];
  }
  t(syncData, node) {
    switch (node) {
      case "settings.json":
        return $1gc(syncData.content).settings;
    }
    return null;
  }
  u(uri, profile) {
    const resource = this.d.joinPath(uri, "keybindings.json");
    const comparableResource = profile ? profile.keybindingsResource : this.d.joinPath(uri, $Ajc_1.a);
    return [{ resource, comparableResource }];
  }
  v(syncData, node) {
    switch (node) {
      case "keybindings.json":
        return $Xgc(syncData.content, !!this.l.getValue($Frb), this.g);
    }
    return null;
  }
  w(uri, profile) {
    const resource = this.d.joinPath(uri, "tasks.json");
    const comparableResource = profile ? profile.tasksResource : this.d.joinPath(uri, $Ajc_1.a);
    return [{ resource, comparableResource }];
  }
  x(syncData, node) {
    switch (node) {
      case "tasks.json":
        return $9gc(syncData.content, this.g);
    }
    return null;
  }
  async y(uri, profile) {
    const content = await this.resolveContent(uri);
    if (content) {
      const syncData = this.L(
        content,
        "snippets"
        /* SyncResource.Snippets */
      );
      if (syncData) {
        const snippets = $6gc(syncData);
        const result = [];
        for (const snippet of Object.keys(snippets)) {
          const resource = this.d.joinPath(uri, snippet);
          const comparableResource = profile ? this.d.joinPath(profile.snippetsHome, snippet) : this.d.joinPath(uri, $Ajc_1.a);
          result.push({ resource, comparableResource });
        }
        return result;
      }
    }
    return [];
  }
  z(syncData, node) {
    return $6gc(syncData)[node] || null;
  }
  A(uri, profile) {
    const resource = this.d.joinPath(uri, "extensions.json");
    const comparableResource = profile ? this.J({
      remote: false,
      syncResource: "extensions",
      profile: profile.id,
      location: void 0,
      collection: void 0,
      ref: void 0,
      node: void 0
    }) : this.d.joinPath(uri, $Ajc_1.a);
    return [{ resource, comparableResource }];
  }
  B(syncData, node) {
    switch (node) {
      case "extensions.json":
        return $Sgc($Rgc(syncData), true);
    }
    return null;
  }
  async C(profile) {
    const { localExtensions } = await this.n.createInstance($Ugc).getLocalExtensions(profile);
    return $Sgc(localExtensions, true);
  }
  D(uri, profile) {
    const resource = this.d.joinPath(uri, "globalState.json");
    const comparableResource = profile ? this.J({
      remote: false,
      syncResource: "globalState",
      profile: profile.id,
      location: void 0,
      collection: void 0,
      ref: void 0,
      node: void 0
    }) : this.d.joinPath(uri, $Ajc_1.a);
    return [{ resource, comparableResource }];
  }
  E(syncData, node) {
    switch (node) {
      case "globalState.json":
        return $nTb(JSON.parse(syncData.content), true);
    }
    return null;
  }
  async F(profile) {
    const localGlobalState = await this.n.createInstance($pTb).getLocalGlobalState(profile);
    return $nTb(localGlobalState, true);
  }
  G(uri, profile) {
    const resource = this.d.joinPath(uri, "profiles.json");
    const comparableResource = this.J({
      remote: false,
      syncResource: "profiles",
      profile: this.k.defaultProfile.id,
      location: void 0,
      collection: void 0,
      ref: void 0,
      node: void 0
    });
    return [{ resource, comparableResource }];
  }
  H(syncData, node) {
    switch (node) {
      case "profiles.json":
        return $ro(JSON.parse(syncData.content), {});
    }
    return null;
  }
  async I(profile) {
    return $Tic(this.k.profiles.filter((p) => !p.isDefault && !p.isTransient), true);
  }
  J(syncResourceUriInfo) {
    const authority = syncResourceUriInfo.remote ? $Ajc_1.b : $Ajc_1.c;
    const paths = [];
    if (syncResourceUriInfo.location) {
      paths.push(`scheme:${syncResourceUriInfo.location.scheme}`);
      paths.push(`authority:${syncResourceUriInfo.location.authority}`);
      paths.push($Ef(syncResourceUriInfo.location.path, "/"));
    }
    paths.push(`syncResource:${syncResourceUriInfo.syncResource}`);
    paths.push(`profile:${syncResourceUriInfo.profile}`);
    if (syncResourceUriInfo.collection) {
      paths.push(`collection:${syncResourceUriInfo.collection}`);
    }
    if (syncResourceUriInfo.ref) {
      paths.push(`ref:${syncResourceUriInfo.ref}`);
    }
    if (syncResourceUriInfo.node) {
      paths.push(syncResourceUriInfo.node);
    }
    return this.d.joinPath(URI.from({ scheme: $4rb, authority, path: `/`, query: syncResourceUriInfo.location?.query, fragment: syncResourceUriInfo.location?.fragment }), ...paths);
  }
  K(uri) {
    if (uri.scheme !== $4rb) {
      return void 0;
    }
    const paths = [];
    while (uri.path !== "/") {
      paths.unshift(this.d.basename(uri));
      uri = this.d.dirname(uri);
    }
    if (paths.length < 2) {
      return void 0;
    }
    const remote = uri.authority === $Ajc_1.b;
    let scheme;
    let authority;
    const locationPaths = [];
    let syncResource;
    let profile;
    let collection;
    let ref;
    let node;
    while (paths.length) {
      const path2 = paths.shift();
      if (path2.startsWith("scheme:")) {
        scheme = path2.substring("scheme:".length);
      } else if (path2.startsWith("authority:")) {
        authority = path2.substring("authority:".length);
      } else if (path2.startsWith("syncResource:")) {
        syncResource = path2.substring("syncResource:".length);
      } else if (path2.startsWith("profile:")) {
        profile = path2.substring("profile:".length);
      } else if (path2.startsWith("collection:")) {
        collection = path2.substring("collection:".length);
      } else if (path2.startsWith("ref:")) {
        ref = path2.substring("ref:".length);
      } else if (!syncResource) {
        locationPaths.push(path2);
      } else {
        node = path2;
      }
    }
    return {
      remote,
      syncResource,
      profile,
      collection,
      ref,
      node,
      location: scheme && authority !== void 0 ? this.d.joinPath(URI.from({ scheme, authority, query: uri.query, fragment: uri.fragment, path: "/" }), ...locationPaths) : void 0
    };
  }
  L(content, syncResource) {
    try {
      const syncData = JSON.parse(content);
      if ($gTb(syncData)) {
        return syncData;
      }
    } catch (error) {
      this.g.error(error);
    }
    throw new $Rrb(localize(2476, null), "IncompatibleRemoteContent", syncResource);
  }
  async M(syncResource, ref, collection) {
    const content = await this.e.resolveResourceContent(syncResource, ref, collection);
    return { ref, content };
  }
};
$Ajc = $Ajc_1 = __decorate([
  __param(0, $Mrb),
  __param(1, $Nrb),
  __param(2, $2rb),
  __param(3, $5l),
  __param(4, $7i),
  __param(5, $Dq),
  __param(6, $ul),
  __param(7, $7l),
  __param(8, $tj),
  __param(9, $Yi)
], $Ajc);

// out-build/vs/platform/extensionManagement/common/unsupportedExtensionsMigration.js
async function $4_b(extensionManagementService, galleryService, extensionStorageService, extensionEnablementService, logService) {
  try {
    const extensionsControlManifest = await extensionManagementService.getExtensionsControlManifest();
    if (!extensionsControlManifest.deprecated) {
      return;
    }
    const installed = await extensionManagementService.getInstalled(
      1
      /* ExtensionType.User */
    );
    for (const [unsupportedExtensionId, deprecated] of Object.entries(extensionsControlManifest.deprecated)) {
      if (!deprecated?.extension) {
        continue;
      }
      const { id: preReleaseExtensionId, autoMigrate, preRelease } = deprecated.extension;
      if (!autoMigrate) {
        continue;
      }
      const unsupportedExtension = installed.find((i) => $8p(i.identifier, { id: unsupportedExtensionId }));
      if (!unsupportedExtension) {
        continue;
      }
      const gallery = (await galleryService.getExtensions([{ id: preReleaseExtensionId, preRelease }], { targetPlatform: await extensionManagementService.getTargetPlatform(), compatible: true }, CancellationToken.None))[0];
      if (!gallery) {
        logService.info(`Skipping migrating '${unsupportedExtension.identifier.id}' extension because, the comaptible target '${preReleaseExtensionId}' extension is not found`);
        continue;
      }
      try {
        logService.info(`Migrating '${unsupportedExtension.identifier.id}' extension to '${preReleaseExtensionId}' extension...`);
        const isUnsupportedExtensionEnabled = !extensionEnablementService.getDisabledExtensions().some((e) => $8p(e, unsupportedExtension.identifier));
        await extensionManagementService.uninstall(unsupportedExtension);
        logService.info(`Uninstalled the unsupported extension '${unsupportedExtension.identifier.id}'`);
        let preReleaseExtension = installed.find((i) => $8p(i.identifier, { id: preReleaseExtensionId }));
        if (!preReleaseExtension || !preReleaseExtension.isPreReleaseVersion && isUnsupportedExtensionEnabled) {
          preReleaseExtension = await extensionManagementService.installFromGallery(gallery, {
            installPreReleaseVersion: true,
            isMachineScoped: unsupportedExtension.isMachineScoped,
            operation: 4
            /* InstallOperation.Migrate */
          });
          logService.info(`Installed the pre-release extension '${preReleaseExtension.identifier.id}'`);
          if (!isUnsupportedExtensionEnabled) {
            await extensionEnablementService.disableExtension(preReleaseExtension.identifier);
            logService.info(`Disabled the pre-release extension '${preReleaseExtension.identifier.id}' because the unsupported extension '${unsupportedExtension.identifier.id}' is disabled`);
          }
          if (autoMigrate.storage) {
            extensionStorageService.addToMigrationList($$p(unsupportedExtension.manifest.publisher, unsupportedExtension.manifest.name), $$p(preReleaseExtension.manifest.publisher, preReleaseExtension.manifest.name));
            logService.info(`Added pre-release extension to the storage migration list`);
          }
        }
        logService.info(`Migrated '${unsupportedExtension.identifier.id}' extension to '${preReleaseExtensionId}' extension.`);
      } catch (error) {
        logService.error(error);
      }
    }
  } catch (error) {
    logService.error(error);
  }
}

// out-build/vs/code/electron-utility/sharedProcess/contrib/extensions.js
var $xmc = class $xmc2 extends $0c {
  constructor(extensionManagementService, extensionGalleryService, extensionStorageService, extensionEnablementService, storageService, logService) {
    super();
    extensionManagementService.cleanUp();
    $4_b(extensionManagementService, extensionGalleryService, extensionStorageService, extensionEnablementService, logService);
    $Zw.removeOutdatedExtensionVersions(extensionManagementService, storageService);
  }
};
$xmc = __decorate([
  __param(0, $ir),
  __param(1, $Gp),
  __param(2, $Yw),
  __param(3, $Mp),
  __param(4, $Dq),
  __param(5, $uk)
], $xmc);

// 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/lifecycle/node/sharedProcessLifecycleService.js
var $ymc = $Zi("sharedProcessLifecycleService");
var $zmc = class $zmc2 extends $0c {
  constructor(b) {
    super();
    this.b = b;
    this.a = this.B(new $De());
    this.onWillShutdown = this.a.event;
  }
  fireOnWillShutdown() {
    this.b.trace("Lifecycle#onWillShutdown.fire()");
    this.a.fire();
  }
};
$zmc = __decorate([
  __param(0, $uk)
], $zmc);

// out-build/vs/platform/remoteTunnel/node/remoteTunnelService.js
import { spawn } from "child_process";
import { hostname, homedir } from "os";

// out-build/vs/base/node/nodeStreams.js
import { Transform } from "stream";
var $TY = class extends Transform {
  constructor(splitter) {
    super();
    if (typeof splitter === "number") {
      this.b = splitter;
      this.c = 1;
    } else {
      const buf = Buffer.isBuffer(splitter) ? splitter : Buffer.from(splitter);
      this.b = buf.length === 1 ? buf[0] : buf;
      this.c = buf.length;
    }
  }
  _transform(chunk, _encoding, callback) {
    if (!this.a) {
      this.a = chunk;
    } else {
      this.a = Buffer.concat([this.a, chunk]);
    }
    let offset = 0;
    while (offset < this.a.length) {
      const index = typeof this.b === "number" ? this.a.indexOf(this.b, offset) : $8e(this.a, this.b, offset);
      if (index === -1) {
        break;
      }
      this.push(this.a.slice(offset, index + this.c));
      offset = index + this.c;
    }
    this.a = offset === this.a.length ? void 0 : this.a.slice(offset);
    callback();
  }
  _flush(callback) {
    if (this.a) {
      this.push(this.a);
    }
    callback();
  }
};

// out-build/vs/platform/remoteTunnel/node/remoteTunnelService.js
var restartTunnelOnConfigurationChanges = [
  $tmc,
  $umc
];
var TUNNEL_ACCESS_SESSION = "remoteTunnelSession";
var TUNNEL_ACCESS_IS_SERVICE = "remoteTunnelIsService";
var $Amc = class $Amc2 extends $0c {
  constructor(y, z, C, loggerService, sharedProcessLifecycleService, D, F) {
    super();
    this.y = y;
    this.z = z;
    this.C = C;
    this.D = D;
    this.F = F;
    this.f = new $De();
    this.onDidTokenFailed = this.f.event;
    this.g = new $De();
    this.onDidChangeTunnelStatus = this.g.event;
    this.h = new $De();
    this.onDidChangeMode = this.h.event;
    this.n = $rmc;
    this.w = false;
    this.I = (a, isErr) => {
      if (isErr) {
        this.j.error(a);
      } else {
        this.j.info(a);
      }
    };
    this.j = this.B(loggerService.createLogger($Ah(C.logsHome, `${$vmc}.log`), { id: $vmc, name: $wmc }));
    this.t = new $Wh(100);
    this.B(this.j.onDidChangeLogLevel((l) => this.j.info("Log level changed to " + $Jk(l))));
    this.B(sharedProcessLifecycleService.onWillShutdown(() => {
      this.r?.cancel();
      this.r = void 0;
      this.dispose();
    }));
    this.B(D.onDidChangeConfiguration((e) => {
      if (restartTunnelOnConfigurationChanges.some((c) => e.affectsConfiguration(c))) {
        this.t.trigger(() => this.L());
      }
    }));
    this.n = this.R();
    this.s = TunnelStates.uninitialized;
  }
  async getTunnelStatus() {
    return this.s;
  }
  G(tunnelStatus) {
    this.s = tunnelStatus;
    this.g.fire(tunnelStatus);
  }
  H(mode) {
    if (isSameMode(this.n, mode)) {
      return;
    }
    this.n = mode;
    this.S(mode);
    this.h.fire(this.n);
    if (mode.active) {
      this.j.info(`Session updated: ${mode.session.accountLabel} (${mode.session.providerId}) (service=${mode.asService})`);
      if (mode.session.token) {
        this.j.info(`Session token updated: ${mode.session.accountLabel} (${mode.session.providerId})`);
      }
    } else {
      this.j.info(`Session reset`);
    }
  }
  getMode() {
    return Promise.resolve(this.n);
  }
  async initialize(mode) {
    if (this.w) {
      return this.s;
    }
    this.w = true;
    this.H(mode);
    try {
      await this.t.trigger(() => this.L());
    } catch (e) {
      this.j.error(e);
    }
    return this.s;
  }
  J() {
    if (!this.u) {
      let binParentLocation;
      if ($m) {
        binParentLocation = this.C.appRoot;
      } else {
        binParentLocation = $yc($yc(this.C.appRoot));
      }
      this.u = $vc(binParentLocation, "bin", `${this.z.tunnelApplicationName}${$l ? ".exe" : ""}`);
    }
    return this.u;
  }
  async startTunnel(mode) {
    if (isSameMode(this.n, mode) && this.s.type !== "disconnected") {
      return this.s;
    }
    this.H(mode);
    try {
      await this.t.trigger(() => this.L());
    } catch (e) {
      this.j.error(e);
    }
    return this.s;
  }
  async stopTunnel() {
    if (this.r) {
      this.r.cancel();
      this.r = void 0;
    }
    if (this.n.active) {
      const needsServiceUninstall = this.n.asService;
      this.H($rmc);
      try {
        if (needsServiceUninstall) {
          this.O("uninstallService", ["service", "uninstall"]);
        }
      } catch (e) {
        this.j.error(e);
      }
    }
    try {
      await this.O("stop", ["kill"]);
    } catch (e) {
      this.j.error(e);
    }
    this.G(TunnelStates.disconnected());
  }
  async L() {
    this.y.publicLog2("remoteTunnel.enablement", {
      enabled: this.n.active,
      service: this.n.active && this.n.asService
    });
    if (this.r) {
      this.r.cancel();
      this.r = void 0;
    }
    let output = "";
    let isServiceInstalled = false;
    const onOutput = (a, isErr) => {
      if (isErr) {
        this.j.error(a);
      } else {
        output += a;
      }
      if (!this.C.isBuilt && a.startsWith("   Compiling")) {
        this.G(TunnelStates.connecting(localize(2059, null)));
      }
    };
    const statusProcess = this.O("status", ["status"], onOutput);
    this.r = statusProcess;
    try {
      await statusProcess;
      if (this.r !== statusProcess) {
        return;
      }
      let status;
      try {
        status = JSON.parse(output.trim().split("\n").find((l) => l.startsWith("{")));
      } catch (e) {
        this.j.error(`Could not parse status output: ${JSON.stringify(output.trim())}`);
        this.G(TunnelStates.disconnected());
        return;
      }
      isServiceInstalled = status.service_installed;
      this.j.info(status.tunnel ? "Other tunnel running, attaching..." : "No other tunnel running");
      if (!status.tunnel && !this.n.active) {
        this.G(TunnelStates.disconnected());
        return;
      }
    } catch (e) {
      this.j.error(e);
      this.G(TunnelStates.disconnected());
      return;
    } finally {
      if (this.r === statusProcess) {
        this.r = void 0;
      }
    }
    const session = this.n.active ? this.n.session : void 0;
    if (session && session.token) {
      const token = session.token;
      this.G(TunnelStates.connecting(localize(2060, null, session.accountLabel, session.providerId)));
      const onLoginOutput = (a, isErr) => {
        a = a.replaceAll(token, "*".repeat(4));
        onOutput(a, isErr);
      };
      const loginProcess = this.O("login", ["user", "login", "--provider", session.providerId, "--log", $Jk(this.j.getLevel())], onLoginOutput, { VSCODE_CLI_ACCESS_TOKEN: token });
      this.r = loginProcess;
      try {
        await loginProcess;
        if (this.r !== loginProcess) {
          return;
        }
      } catch (e) {
        this.j.error(e);
        this.r = void 0;
        this.f.fire(session);
        this.G(TunnelStates.disconnected(session));
        return;
      }
    }
    const hostName = this.Q();
    if (hostName) {
      this.G(TunnelStates.connecting(localize(2061, null, hostName)));
    } else {
      this.G(TunnelStates.connecting(localize(2062, null)));
    }
    const args = ["--accept-server-license-terms", "--log", $Jk(this.j.getLevel())];
    if (hostName) {
      args.push("--name", hostName);
    } else {
      args.push("--random-name");
    }
    let serviceInstallFailed = false;
    if (this.n.active && this.n.asService && !isServiceInstalled) {
      serviceInstallFailed = await this.M(args) === false;
    }
    return this.N(session, args, serviceInstallFailed);
  }
  async M(args) {
    let status;
    try {
      status = await this.O("serviceInstall", ["service", "install", ...args]);
    } catch (e) {
      this.j.error(e);
      status = 1;
    }
    if (status !== 0) {
      const msg = localize(2063, null);
      this.j.warn(msg);
      this.G(TunnelStates.connecting(msg));
      return false;
    }
    return true;
  }
  async N(session, args, serviceInstallFailed) {
    args.push("--parent-process-id", String(process.pid));
    if (this.P()) {
      args.push("--no-sleep");
    }
    let isAttached = false;
    const serveCommand = this.O("tunnel", args, (message, isErr) => {
      if (isErr) {
        this.j.error(message);
      } else {
        this.j.info(message);
      }
      if (message.includes("Connected to an existing tunnel process")) {
        isAttached = true;
      }
      const m = message.match(/Open this link in your browser (https:\/\/([^\/\s]+)\/([^\/\s]+)\/([^\/\s]+))/);
      if (m) {
        const info = { link: m[1], domain: m[2], tunnelName: m[4], isAttached };
        this.G(TunnelStates.connected(info, serviceInstallFailed));
      } else if (message.match(/error refreshing token/)) {
        serveCommand.cancel();
        this.f.fire(session);
        this.G(TunnelStates.disconnected(session));
      }
    });
    this.r = serveCommand;
    serveCommand.finally(() => {
      if (serveCommand === this.r) {
        this.j.info(`tunnel process terminated`);
        this.r = void 0;
        this.n = $rmc;
        this.G(TunnelStates.disconnected());
      }
    });
  }
  O(logLabel, commandArgs, onOutput = this.I, env2) {
    return $Mh((token) => {
      return new Promise((resolve, reject) => {
        if (token.isCancellationRequested) {
          resolve(-1);
        }
        let tunnelProcess;
        const stdio = ["ignore", "pipe", "pipe"];
        token.onCancellationRequested(() => {
          if (tunnelProcess) {
            this.j.info(`${logLabel} terminating(${tunnelProcess.pid})`);
            tunnelProcess.kill();
          }
        });
        if (!this.C.isBuilt) {
          onOutput("Building tunnel CLI from sources and run\n", false);
          onOutput(`${logLabel} Spawning: cargo run -- tunnel ${commandArgs.join(" ")}
`, false);
          tunnelProcess = spawn("cargo", ["run", "--", "tunnel", ...commandArgs], { cwd: $vc(this.C.appRoot, "cli"), stdio, env: { ...process.env, RUST_BACKTRACE: "1", ...env2 } });
        } else {
          onOutput("Running tunnel CLI\n", false);
          const tunnelCommand = this.J();
          onOutput(`${logLabel} Spawning: ${tunnelCommand} tunnel ${commandArgs.join(" ")}
`, false);
          tunnelProcess = spawn(tunnelCommand, ["tunnel", ...commandArgs], { cwd: homedir(), stdio, env: { ...process.env, ...env2 } });
        }
        tunnelProcess.stdout.pipe(new $TY("\n")).on("data", (data) => {
          if (tunnelProcess) {
            const message = data.toString();
            onOutput(message, false);
          }
        });
        tunnelProcess.stderr.pipe(new $TY("\n")).on("data", (data) => {
          if (tunnelProcess) {
            const message = data.toString();
            onOutput(message, true);
          }
        });
        tunnelProcess.on("exit", (e) => {
          if (tunnelProcess) {
            onOutput(`${logLabel} exit(${tunnelProcess.pid}): + ${e} `, false);
            tunnelProcess = void 0;
            resolve(e || 0);
          }
        });
        tunnelProcess.on("error", (e) => {
          if (tunnelProcess) {
            onOutput(`${logLabel} error(${tunnelProcess.pid}): + ${e} `, true);
            tunnelProcess = void 0;
            reject();
          }
        });
      });
    });
  }
  async getTunnelName() {
    return this.Q();
  }
  P() {
    return !!this.D.getValue($umc);
  }
  Q() {
    let name = this.D.getValue($tmc) || hostname();
    name = name.replace(/^-+/g, "").replace(/[^\w-]/g, "").substring(0, 20);
    return name || void 0;
  }
  R() {
    try {
      const tunnelAccessSession = this.F.get(
        TUNNEL_ACCESS_SESSION,
        -1
        /* StorageScope.APPLICATION */
      );
      const asService = this.F.getBoolean(TUNNEL_ACCESS_IS_SERVICE, -1, false);
      if (tunnelAccessSession) {
        const session = JSON.parse(tunnelAccessSession);
        if (session && $yg(session.accountLabel) && $yg(session.sessionId) && $yg(session.providerId)) {
          return { active: true, session, asService };
        }
        this.j.error("Problems restoring session from storage, invalid format", session);
      }
    } catch (e) {
      this.j.error("Problems restoring session from storage", e);
    }
    return $rmc;
  }
  S(mode) {
    if (mode.active) {
      const sessionWithoutToken = {
        providerId: mode.session.providerId,
        sessionId: mode.session.sessionId,
        accountLabel: mode.session.accountLabel
      };
      this.F.store(
        TUNNEL_ACCESS_SESSION,
        JSON.stringify(sessionWithoutToken),
        -1,
        1
        /* StorageTarget.MACHINE */
      );
      this.F.store(
        TUNNEL_ACCESS_IS_SERVICE,
        mode.asService,
        -1,
        1
        /* StorageTarget.MACHINE */
      );
    } else {
      this.F.remove(
        TUNNEL_ACCESS_SESSION,
        -1
        /* StorageScope.APPLICATION */
      );
      this.F.remove(
        TUNNEL_ACCESS_IS_SERVICE,
        -1
        /* StorageScope.APPLICATION */
      );
    }
  }
};
$Amc = __decorate([
  __param(0, $tm),
  __param(1, $Nk),
  __param(2, $8i),
  __param(3, $vk),
  __param(4, $ymc),
  __param(5, $tj),
  __param(6, $Dq)
], $Amc);
function isSameSession(a1, a2) {
  if (a1 && a2) {
    return a1.sessionId === a2.sessionId && a1.providerId === a2.providerId && a1.token === a2.token;
  }
  return a1 === a2;
}
var isSameMode = (a, b) => {
  if (a.active !== b.active) {
    return false;
  } else if (a.active && b.active) {
    return a.asService === b.asService && isSameSession(a.session, b.session);
  } else {
    return true;
  }
};

// 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/extensionRecommendations/common/extensionRecommendationsIpc.js
var $Bmc = class {
  constructor(a) {
    this.a = a;
  }
  get ignoredRecommendations() {
    throw new Error("not supported");
  }
  promptImportantExtensionsInstallNotification(extensionRecommendations) {
    return this.a.call("promptImportantExtensionsInstallNotification", [extensionRecommendations]);
  }
  promptWorkspaceRecommendations(recommendations) {
    throw new Error("not supported");
  }
  hasToIgnoreRecommendationNotifications() {
    throw new Error("not supported");
  }
};

// out-build/vs/platform/native/common/nativeHostService.js
var $2lc = class $2lc2 {
  constructor(windowId, mainProcessService) {
    this.windowId = windowId;
    return ProxyChannel.toService(mainProcessService.getChannel("nativeHost"), {
      context: windowId,
      properties: (() => {
        const properties = /* @__PURE__ */ new Map();
        properties.set("windowId", windowId);
        return properties;
      })()
    });
  }
};
$2lc = __decorate([
  __param(1, $HOb)
], $2lc);

// out-build/vs/platform/userDataSync/common/userDataAutoSyncService.js
var disableMachineEventuallyKey = "sync.disableMachineEventually";
var sessionIdKey = "sync.sessionId";
var storeUrlKey = "sync.storeUrl";
var productQualityKey = "sync.productQuality";
var $Wic = class $Wic2 extends $0c {
  get n() {
    const value = this.H.get(
      storeUrlKey,
      -1
      /* StorageScope.APPLICATION */
    );
    return value ? URI.parse(value) : void 0;
  }
  set n(syncUrl) {
    if (syncUrl) {
      this.H.store(
        storeUrlKey,
        syncUrl.toString(),
        -1,
        1
        /* StorageTarget.MACHINE */
      );
    } else {
      this.H.remove(
        storeUrlKey,
        -1
        /* StorageScope.APPLICATION */
      );
    }
  }
  get s() {
    return this.H.get(
      productQualityKey,
      -1
      /* StorageScope.APPLICATION */
    );
  }
  set s(productQuality) {
    if (productQuality) {
      this.H.store(
        productQualityKey,
        productQuality,
        -1,
        1
        /* StorageTarget.MACHINE */
      );
    } else {
      this.H.remove(
        productQualityKey,
        -1
        /* StorageScope.APPLICATION */
      );
    }
  }
  constructor(productService, u, w, y, z, C, D, F, G, H) {
    super();
    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.a = this.B(new $$c());
    this.b = 0;
    this.c = void 0;
    this.g = false;
    this.h = this.B(new $De());
    this.onError = this.h.event;
    this.S = [];
    this.f = this.B(new $Xh(this.U()));
    this.j = this.n;
    this.n = u.userDataSyncStore?.url;
    this.r = this.s;
    this.s = productService.quality;
    if (this.n) {
      this.C.info("Using settings sync service", this.n.toString());
      this.B(u.onDidChangeUserDataSyncStore(() => {
        if (!$th(this.n, u.userDataSyncStore?.url)) {
          this.j = this.n;
          this.n = u.userDataSyncStore?.url;
          if (this.n) {
            this.C.info("Using settings sync service", this.n.toString());
          }
        }
      }));
      if (this.y.isEnabled()) {
        this.C.info("Auto Sync is enabled.");
      } else {
        this.C.info("Auto Sync is disabled.");
      }
      this.I();
      if (this.Q()) {
        this.P();
      }
      this.B(D.onDidChangeAccount(() => this.I()));
      this.B(w.onDidChangeDonotMakeRequestsUntil(() => this.I()));
      this.B(z.onDidChangeLocal((source) => this.triggerSync([source], false, false)));
      this.B(Event.filter(this.y.onDidChangeResourceEnablement, ([, enabled]) => enabled)(() => this.triggerSync(["resourceEnablement"], false, false)));
      this.B(this.u.onDidChangeUserDataSyncStore(() => this.triggerSync(["userDataSyncStoreChanged"], false, false)));
    }
  }
  I() {
    const { enabled, message } = this.L();
    if (enabled) {
      if (this.a.value === void 0) {
        this.a.value = new AutoSync(this.j, 1e3 * 60 * 5, this.u, this.w, this.z, this.G, this.C, this.F, this.H);
        this.a.value.register(this.a.value.onDidStartSync(() => this.c = (/* @__PURE__ */ new Date()).getTime()));
        this.a.value.register(this.a.value.onDidFinishSync((e) => this.O(e)));
        if (this.J()) {
          this.a.value.start();
        }
      }
    } else {
      this.f.cancel();
      if (this.a.value !== void 0) {
        if (message) {
          this.C.info(message);
        }
        this.a.clear();
      } else if (message && this.y.isEnabled()) {
        this.C.info(message);
      }
    }
  }
  // For tests purpose only
  J() {
    return true;
  }
  L() {
    if (!this.y.isEnabled()) {
      return { enabled: false, message: "Auto Sync: Disabled." };
    }
    if (!this.D.account) {
      return { enabled: false, message: "Auto Sync: Suspended until auth token is available." };
    }
    if (this.w.donotMakeRequestsUntil) {
      return { enabled: false, message: `Auto Sync: Suspended until ${$mn(this.w.donotMakeRequestsUntil)} because server is not accepting requests until then.` };
    }
    if (this.g) {
      return { enabled: false, message: "Auto Sync: Suspended until restart." };
    }
    return { enabled: true };
  }
  async turnOn() {
    this.R();
    this.j = this.n;
    this.M(true);
  }
  async turnOff(everywhere, softTurnOffOnError, donotRemoveMachine) {
    try {
      if (this.D.account && !donotRemoveMachine) {
        await this.G.removeCurrentMachine();
      }
      this.M(false);
      this.H.remove(
        sessionIdKey,
        -1
        /* StorageScope.APPLICATION */
      );
      if (everywhere) {
        this.F.publicLog2("sync/turnOffEveryWhere");
        await this.z.reset();
      } else {
        await this.z.resetLocal();
      }
    } catch (error) {
      this.C.error(error);
      if (softTurnOffOnError) {
        this.M(false);
      } else {
        throw error;
      }
    }
  }
  M(enabled) {
    if (this.y.isEnabled() !== enabled) {
      this.y.setEnablement(enabled);
      this.I();
    }
  }
  N() {
    return !!this.r && !!this.s && this.r !== this.s;
  }
  async O(error) {
    if (!error) {
      this.b = 0;
      return;
    }
    const userDataSyncError = $Rrb.toUserDataSyncError(error);
    if (userDataSyncError instanceof $Trb) {
      this.F.publicLog2(`autosync/error`, { code: userDataSyncError.code, service: this.u.userDataSyncStore.url.toString() });
    }
    if (userDataSyncError.code === "SessionExpired") {
      await this.turnOff(
        false,
        true
        /* force soft turnoff on error */
      );
      this.C.info("Auto Sync: Turned off sync because current session is expired");
    } else if (userDataSyncError.code === "TurnedOff") {
      await this.turnOff(
        false,
        true
        /* force soft turnoff on error */
      );
      this.C.info("Auto Sync: Turned off sync because sync is turned off in the cloud");
    } else if (userDataSyncError.code === "LocalTooManyRequests") {
      this.g = true;
      this.C.info("Auto Sync: Suspended sync because of making too many requests to server");
      this.I();
    } else if (userDataSyncError.code === "RemoteTooManyRequests") {
      await this.turnOff(
        false,
        true,
        true
        /* do not disable machine because disabling a machine makes request to server and can fail with TooManyRequests */
      );
      this.P();
      this.C.info("Auto Sync: Turned off sync because of making too many requests to server");
    } else if (userDataSyncError.code === "MethodNotFound") {
      await this.turnOff(
        false,
        true
        /* force soft turnoff on error */
      );
      this.C.info("Auto Sync: Turned off sync because current client is making requests to server that are not supported");
    } else if (userDataSyncError.code === "UpgradeRequired" || userDataSyncError.code === "Gone") {
      await this.turnOff(
        false,
        true,
        true
        /* do not disable machine because disabling a machine makes request to server and can fail with upgrade required or gone */
      );
      this.P();
      this.C.info("Auto Sync: Turned off sync because current client is not compatible with server. Requires client upgrade.");
    } else if (userDataSyncError.code === "IncompatibleLocalContent") {
      await this.turnOff(
        false,
        true
        /* force soft turnoff on error */
      );
      this.C.info(`Auto Sync: Turned off sync because server has ${userDataSyncError.resource} content with newer version than of client. Requires client upgrade.`);
    } else if (userDataSyncError.code === "IncompatibleRemoteContent") {
      await this.turnOff(
        false,
        true
        /* force soft turnoff on error */
      );
      this.C.info(`Auto Sync: Turned off sync because server has ${userDataSyncError.resource} content with older version than of client. Requires server reset.`);
    } else if (userDataSyncError.code === "ServiceChanged" || userDataSyncError.code === "DefaultServiceChanged") {
      if ($r && userDataSyncError.code === "DefaultServiceChanged" && !this.N()) {
        await this.turnOff(
          false,
          true
          /* force soft turnoff on error */
        );
        this.C.info("Auto Sync: Turned off sync because default sync service is changed.");
      } else {
        await this.turnOff(
          false,
          true,
          true
          /* do not disable machine */
        );
        await this.turnOn();
        this.C.info("Auto Sync: Sync Service changed. Turned off auto sync, reset local state and turned on auto sync.");
      }
    } else {
      this.C.error(userDataSyncError);
      this.b++;
    }
    this.h.fire(userDataSyncError);
  }
  async P() {
    this.H.store(
      disableMachineEventuallyKey,
      true,
      -1,
      1
      /* StorageTarget.MACHINE */
    );
    await $1h(1e3 * 60 * 10);
    if (!this.Q()) {
      return;
    }
    this.R();
    if (!this.y.isEnabled() && this.D.account) {
      await this.G.removeCurrentMachine();
    }
  }
  Q() {
    return this.H.getBoolean(disableMachineEventuallyKey, -1, false);
  }
  R() {
    this.H.remove(
      disableMachineEventuallyKey,
      -1
      /* StorageScope.APPLICATION */
    );
  }
  async triggerSync(sources, skipIfSyncedRecently, disableCache) {
    if (this.a.value === void 0) {
      return this.f.cancel();
    }
    if (skipIfSyncedRecently && this.c && Math.round(((/* @__PURE__ */ new Date()).getTime() - this.c) / 1e3) < 10) {
      this.C.debug("Auto Sync: Skipped. Limited to once per 10 seconds.");
      return;
    }
    this.S.push(...sources);
    return this.f.trigger(async () => {
      this.C.trace("activity sources", ...this.S);
      const providerId = this.D.account?.authenticationProviderId || "";
      this.F.publicLog2("sync/triggered", { sources: this.S, providerId });
      this.S = [];
      if (this.a.value) {
        await this.a.value.sync("Activity", disableCache);
      }
    }, this.b ? this.U() * 1 * Math.min(Math.pow(2, this.b), 60) : this.U());
  }
  U() {
    return 2e3;
  }
};
$Wic = __decorate([
  __param(0, $Nk),
  __param(1, $Lrb),
  __param(2, $Mrb),
  __param(3, $Wrb),
  __param(4, $Xrb),
  __param(5, $2rb),
  __param(6, $GRb),
  __param(7, $tm),
  __param(8, $yrb),
  __param(9, $Dq)
], $Wic);
var AutoSync = class _AutoSync extends $0c {
  static {
    this.a = "Interval";
  }
  constructor(m, n, r, s, u, w, y, z, C) {
    super();
    this.m = m;
    this.n = n;
    this.r = r;
    this.s = s;
    this.u = u;
    this.w = w;
    this.y = y;
    this.z = z;
    this.C = C;
    this.b = this.B(new $$c());
    this.c = this.B(new $De());
    this.onDidStartSync = this.c.event;
    this.f = this.B(new $De());
    this.onDidFinishSync = this.f.event;
    this.g = null;
  }
  start() {
    this.B(this.onDidFinishSync(() => this.D()));
    this.B($8c(() => {
      if (this.j) {
        this.j.cancel();
        this.y.info("Auto sync: Cancelled sync that is in progress");
        this.j = void 0;
      }
      this.h?.stop();
      this.y.info("Auto Sync: Stopped");
    }));
    this.sync(_AutoSync.a, false);
  }
  D() {
    this.b.value = $2h(() => {
      this.sync(_AutoSync.a, false);
      this.b.value = void 0;
    }, this.n);
  }
  sync(reason, disableCache) {
    const syncPromise = $Mh(async (token) => {
      if (this.j) {
        try {
          this.y.debug("Auto Sync: Waiting until sync is finished.");
          await this.j;
        } catch (error) {
          if ($eb(error)) {
            return;
          }
        }
      }
      return this.H(reason, disableCache, token);
    });
    this.j = syncPromise;
    this.j.finally(() => this.j = void 0);
    return this.j;
  }
  F() {
    return this.m !== void 0 && !$th(this.m, this.r.userDataSyncStore?.url);
  }
  async G() {
    const previous = await this.r.getPreviousUserDataSyncStore();
    const current = this.r.userDataSyncStore;
    return !!current && !!previous && (!$th(current.defaultUrl, previous.defaultUrl) || !$th(current.insidersUrl, previous.insidersUrl) || !$th(current.stableUrl, previous.stableUrl));
  }
  async H(reason, disableCache, token) {
    this.y.info(`Auto Sync: Triggered by ${reason}`);
    this.c.fire();
    let error;
    try {
      await this.I(disableCache, token);
    } catch (e) {
      this.y.error(e);
      error = e;
      if ($Rrb.toUserDataSyncError(e).code === "MethodNotFound") {
        try {
          this.y.info("Auto Sync: Client is making invalid requests. Cleaning up data...");
          await this.u.cleanUpRemoteData();
          this.y.info("Auto Sync: Retrying sync...");
          await this.I(disableCache, token);
          error = void 0;
        } catch (e1) {
          this.y.error(e1);
          error = e1;
        }
      }
    }
    this.f.fire(error);
  }
  async I(disableCache, token) {
    this.h = await this.u.createSyncTask(this.g, disableCache);
    if (token.isCancellationRequested) {
      return;
    }
    this.g = this.h.manifest;
    if (this.g === null && await this.u.hasPreviouslySynced()) {
      if (this.F()) {
        if (await this.G()) {
          throw new $Trb(
            localize(2462, null),
            "DefaultServiceChanged"
            /* UserDataSyncErrorCode.DefaultServiceChanged */
          );
        } else {
          throw new $Trb(
            localize(2463, null),
            "ServiceChanged"
            /* UserDataSyncErrorCode.ServiceChanged */
          );
        }
      } else {
        throw new $Trb(
          localize(2464, null),
          "TurnedOff"
          /* UserDataSyncErrorCode.TurnedOff */
        );
      }
    }
    const sessionId = this.C.get(
      sessionIdKey,
      -1
      /* StorageScope.APPLICATION */
    );
    if (sessionId && this.g && sessionId !== this.g.session) {
      if (this.F()) {
        if (await this.G()) {
          throw new $Trb(
            localize(2465, null),
            "DefaultServiceChanged"
            /* UserDataSyncErrorCode.DefaultServiceChanged */
          );
        } else {
          throw new $Trb(
            localize(2466, null),
            "ServiceChanged"
            /* UserDataSyncErrorCode.ServiceChanged */
          );
        }
      } else {
        throw new $Trb(
          localize(2467, null),
          "SessionExpired"
          /* UserDataSyncErrorCode.SessionExpired */
        );
      }
    }
    const machines = await this.w.getMachines(this.g || void 0);
    if (token.isCancellationRequested) {
      return;
    }
    const currentMachine = machines.find((machine) => machine.isCurrent);
    if (currentMachine?.disabled) {
      throw new $Trb(
        localize(2468, null),
        "TurnedOff"
        /* UserDataSyncErrorCode.TurnedOff */
      );
    }
    const startTime = (/* @__PURE__ */ new Date()).getTime();
    await this.h.run();
    this.z.publicLog2("settingsSync:sync", { duration: (/* @__PURE__ */ new Date()).getTime() - startTime });
    if (this.g === null) {
      try {
        this.g = await this.s.manifest(null);
      } catch (error) {
        throw new $Trb(
          $Kj(error),
          error instanceof $Rrb ? error.code : "Unknown"
          /* UserDataSyncErrorCode.Unknown */
        );
      }
    }
    if (this.g && this.g.session !== sessionId) {
      this.C.store(
        sessionIdKey,
        this.g.session,
        -1,
        1
        /* StorageTarget.MACHINE */
      );
    }
    if (token.isCancellationRequested) {
      return;
    }
    if (!currentMachine) {
      await this.w.addCurrentMachine(this.g || void 0);
    }
  }
  register(t) {
    return super.B(t);
  }
};

// out-build/vs/platform/userDataSync/node/userDataAutoSyncService.js
var $Dmc = class $Dmc2 extends $Wic {
  constructor(productService, userDataSyncStoreManagementService, userDataSyncStoreService, userDataSyncEnablementService, userDataSyncService, nativeHostService, logService, authTokenService, telemetryService, userDataSyncMachinesService, storageService) {
    super(productService, userDataSyncStoreManagementService, userDataSyncStoreService, userDataSyncEnablementService, userDataSyncService, logService, authTokenService, telemetryService, userDataSyncMachinesService, storageService);
    this.B(Event.debounce(Event.any(Event.map(nativeHostService.onDidFocusMainWindow, () => "windowFocus"), Event.map(nativeHostService.onDidOpenMainWindow, () => "windowOpen")), (last, source) => last ? [...last, source] : [source], 1e3)((sources) => this.triggerSync(sources, true, false)));
  }
};
$Dmc = __decorate([
  __param(0, $Nk),
  __param(1, $Lrb),
  __param(2, $Mrb),
  __param(3, $Wrb),
  __param(4, $Xrb),
  __param(5, $ykc),
  __param(6, $2rb),
  __param(7, $GRb),
  __param(8, $tm),
  __param(9, $yrb),
  __param(10, $Dq)
], $Dmc);

// out-build/vs/platform/extensionManagement/common/extensionTipsService.js
var $Nic = class $Nic2 extends $0c {
  constructor(b, c) {
    super();
    this.b = b;
    this.c = c;
    this.a = /* @__PURE__ */ new Map();
    if (this.c.configBasedExtensionTips) {
      Object.entries(this.c.configBasedExtensionTips).forEach(([, value]) => this.a.set(value.configPath, value));
    }
  }
  getConfigBasedTips(folder) {
    return this.f(folder);
  }
  async getImportantExecutableBasedTips() {
    return [];
  }
  async getOtherExecutableBasedTips() {
    return [];
  }
  async f(folder) {
    const result = [];
    for (const [configPath, tip] of this.a) {
      if (tip.configScheme && tip.configScheme !== folder.scheme) {
        continue;
      }
      try {
        const content = (await this.b.readFile($Ah(folder, configPath))).value.toString();
        for (const [key, value] of Object.entries(tip.recommendations)) {
          if (!value.contentPattern || new RegExp(value.contentPattern, "mig").test(content)) {
            result.push({
              extensionId: key,
              extensionName: value.name,
              configName: tip.configName,
              important: !!value.important,
              isExtensionPack: !!value.isExtensionPack,
              whenNotInstalled: value.whenNotInstalled
            });
          }
        }
      } catch (error) {
      }
    }
    return result;
  }
};
$Nic = __decorate([
  __param(0, $ul),
  __param(1, $Nk)
], $Nic);
var promptedExecutableTipsStorageKey = "extensionTips/promptedExecutableTips";
var lastPromptedMediumImpExeTimeStorageKey = "extensionTips/lastPromptedMediumImpExeTime";
var $Oic = class extends $Nic {
  constructor(r, s, t, u, w, z, fileService, productService) {
    super(fileService, productService);
    this.r = r;
    this.s = s;
    this.t = t;
    this.u = u;
    this.w = w;
    this.z = z;
    this.g = /* @__PURE__ */ new Map();
    this.h = /* @__PURE__ */ new Map();
    this.j = /* @__PURE__ */ new Map();
    this.m = /* @__PURE__ */ new Map();
    this.n = /* @__PURE__ */ new Map();
    if (productService.exeBasedExtensionTips) {
      Object.entries(productService.exeBasedExtensionTips).forEach(([key, exeBasedExtensionTip]) => {
        const highImportanceRecommendations = [];
        const mediumImportanceRecommendations = [];
        const otherRecommendations = [];
        Object.entries(exeBasedExtensionTip.recommendations).forEach(([extensionId, value]) => {
          if (value.important) {
            if (exeBasedExtensionTip.important) {
              highImportanceRecommendations.push({ extensionId, extensionName: value.name, isExtensionPack: !!value.isExtensionPack });
            } else {
              mediumImportanceRecommendations.push({ extensionId, extensionName: value.name, isExtensionPack: !!value.isExtensionPack });
            }
          } else {
            otherRecommendations.push({ extensionId, extensionName: value.name, isExtensionPack: !!value.isExtensionPack });
          }
        });
        if (highImportanceRecommendations.length) {
          this.g.set(key, { exeFriendlyName: exeBasedExtensionTip.friendlyName, windowsPath: exeBasedExtensionTip.windowsPath, recommendations: highImportanceRecommendations });
        }
        if (mediumImportanceRecommendations.length) {
          this.h.set(key, { exeFriendlyName: exeBasedExtensionTip.friendlyName, windowsPath: exeBasedExtensionTip.windowsPath, recommendations: mediumImportanceRecommendations });
        }
        if (otherRecommendations.length) {
          this.j.set(key, { exeFriendlyName: exeBasedExtensionTip.friendlyName, windowsPath: exeBasedExtensionTip.windowsPath, recommendations: otherRecommendations });
        }
      });
    }
    $2h(async () => {
      await this.C();
      this.F();
      this.G();
    }, 3e3, this.q);
  }
  async getImportantExecutableBasedTips() {
    const highImportanceExeTips = await this.O(this.g);
    const mediumImportanceExeTips = await this.O(this.h);
    return [...highImportanceExeTips, ...mediumImportanceExeTips];
  }
  getOtherExecutableBasedTips() {
    return this.O(this.j);
  }
  async C() {
    const highImportanceExeTips = await this.O(this.g);
    const mediumImportanceExeTips = await this.O(this.h);
    const local = await this.u.getInstalled();
    this.m = this.D(highImportanceExeTips, local);
    this.n = this.D(mediumImportanceExeTips, local);
  }
  D(importantExeBasedTips, local) {
    const importantExeBasedRecommendations = /* @__PURE__ */ new Map();
    importantExeBasedTips.forEach((tip) => importantExeBasedRecommendations.set(tip.extensionId.toLowerCase(), tip));
    const { installed, uninstalled: recommendations } = this.N([...importantExeBasedRecommendations.keys()], local);
    for (const extensionId of installed) {
      const tip = importantExeBasedRecommendations.get(extensionId);
      if (tip) {
        this.t.publicLog2("exeExtensionRecommendations:alreadyInstalled", { extensionId, exeName: tip.exeName });
      }
    }
    for (const extensionId of recommendations) {
      const tip = importantExeBasedRecommendations.get(extensionId);
      if (tip) {
        this.t.publicLog2("exeExtensionRecommendations:notInstalled", { extensionId, exeName: tip.exeName });
      }
    }
    const promptedExecutableTips = this.L();
    const tipsByExe = /* @__PURE__ */ new Map();
    for (const extensionId of recommendations) {
      const tip = importantExeBasedRecommendations.get(extensionId);
      if (tip && (!promptedExecutableTips[tip.exeName] || !promptedExecutableTips[tip.exeName].includes(tip.extensionId))) {
        let tips = tipsByExe.get(tip.exeName);
        if (!tips) {
          tips = [];
          tipsByExe.set(tip.exeName, tips);
        }
        tips.push(tip);
      }
    }
    return tipsByExe;
  }
  /**
   * High importance tips are prompted once per restart session
   */
  F() {
    if (this.m.size === 0) {
      return;
    }
    const [exeName, tips] = [...this.m.entries()][0];
    this.H(tips).then((result) => {
      switch (result) {
        case "reacted":
          this.M(tips[0].exeName, tips);
          break;
        case "ignored":
          this.m.delete(exeName);
          break;
        case "incompatibleWindow": {
          const onActiveWindowChange = Event.once(Event.latch(Event.any(this.s.onDidOpenMainWindow, this.s.onDidFocusMainWindow)));
          this.B(onActiveWindowChange(() => this.F()));
          break;
        }
        case "toomany": {
          const disposable = this.B(new $$c());
          disposable.value = $2h(
            () => {
              disposable.dispose();
              this.F();
            },
            60 * 60 * 1e3
            /* 1 hour */
          );
          break;
        }
      }
    });
  }
  /**
   * Medium importance tips are prompted once per 7 days
   */
  G() {
    if (this.n.size === 0) {
      return;
    }
    const lastPromptedMediumExeTime = this.I();
    const timeSinceLastPrompt = Date.now() - lastPromptedMediumExeTime;
    const promptInterval = 7 * 24 * 60 * 60 * 1e3;
    if (timeSinceLastPrompt < promptInterval) {
      const disposable = this.B(new $$c());
      disposable.value = $2h(() => {
        disposable.dispose();
        this.G();
      }, promptInterval - timeSinceLastPrompt);
      return;
    }
    const [exeName, tips] = [...this.n.entries()][0];
    this.H(tips).then((result) => {
      switch (result) {
        case "reacted": {
          this.J(Date.now());
          this.n.delete(exeName);
          this.M(tips[0].exeName, tips);
          const disposable1 = this.B(new $$c());
          disposable1.value = $2h(() => {
            disposable1.dispose();
            this.G();
          }, promptInterval);
          break;
        }
        case "ignored":
          this.n.delete(exeName);
          this.G();
          break;
        case "incompatibleWindow": {
          const onActiveWindowChange = Event.once(Event.latch(Event.any(this.s.onDidOpenMainWindow, this.s.onDidFocusMainWindow)));
          this.B(onActiveWindowChange(() => this.G()));
          break;
        }
        case "toomany": {
          const disposable2 = this.B(new $$c());
          disposable2.value = $2h(
            () => {
              disposable2.dispose();
              this.G();
            },
            60 * 60 * 1e3
            /* 1 hour */
          );
          break;
        }
      }
    });
  }
  async H(tips) {
    const installed = await this.u.getInstalled(
      1
      /* ExtensionType.User */
    );
    const extensions = tips.filter((tip) => !tip.whenNotInstalled || tip.whenNotInstalled.every((id2) => installed.every((local) => !$8p(local.identifier, { id: id2 })))).map(({ extensionId }) => extensionId.toLowerCase());
    return this.z.promptImportantExtensionsInstallNotification({ extensions, source: 3, name: tips[0].exeFriendlyName, searchValue: `@exe:"${tips[0].exeName}"` });
  }
  I() {
    let value = this.w.getNumber(
      lastPromptedMediumImpExeTimeStorageKey,
      -1
      /* StorageScope.APPLICATION */
    );
    if (!value) {
      value = Date.now();
      this.J(value);
    }
    return value;
  }
  J(value) {
    this.w.store(
      lastPromptedMediumImpExeTimeStorageKey,
      value,
      -1,
      1
      /* StorageTarget.MACHINE */
    );
  }
  L() {
    return JSON.parse(this.w.get(promptedExecutableTipsStorageKey, -1, "{}"));
  }
  M(exeName, tips) {
    const promptedExecutableTips = this.L();
    promptedExecutableTips[exeName] = tips.map(({ extensionId }) => extensionId.toLowerCase());
    this.w.store(
      promptedExecutableTipsStorageKey,
      JSON.stringify(promptedExecutableTips),
      -1,
      0
      /* StorageTarget.USER */
    );
  }
  N(recommendationsToSuggest, local) {
    const installed = [], uninstalled = [];
    const installedExtensionsIds = local.reduce((result, i) => {
      result.add(i.identifier.id.toLowerCase());
      return result;
    }, /* @__PURE__ */ new Set());
    recommendationsToSuggest.forEach((id2) => {
      if (installedExtensionsIds.has(id2.toLowerCase())) {
        installed.push(id2);
      } else {
        uninstalled.push(id2);
      }
    });
    return { installed, uninstalled };
  }
  async O(executableTips) {
    const result = [];
    const checkedExecutables = /* @__PURE__ */ new Map();
    for (const exeName of executableTips.keys()) {
      const extensionTip = executableTips.get(exeName);
      if (!extensionTip || !$Yb(extensionTip.recommendations)) {
        continue;
      }
      const exePaths = [];
      if ($l) {
        if (extensionTip.windowsPath) {
          exePaths.push(extensionTip.windowsPath.replace("%USERPROFILE%", () => env["USERPROFILE"]).replace("%ProgramFiles(x86)%", () => env["ProgramFiles(x86)"]).replace("%ProgramFiles%", () => env["ProgramFiles"]).replace("%APPDATA%", () => env["APPDATA"]).replace("%WINDIR%", () => env["WINDIR"]));
        }
      } else {
        exePaths.push($vc("/usr/local/bin", exeName));
        exePaths.push($vc("/usr/bin", exeName));
        exePaths.push($vc(this.r.fsPath, exeName));
      }
      for (const exePath of exePaths) {
        let exists = checkedExecutables.get(exePath);
        if (exists === void 0) {
          exists = await this.b.exists(URI.file(exePath));
          checkedExecutables.set(exePath, exists);
        }
        if (exists) {
          for (const { extensionId, extensionName, isExtensionPack, whenNotInstalled } of extensionTip.recommendations) {
            result.push({
              extensionId,
              extensionName,
              isExtensionPack,
              exeName,
              exeFriendlyName: extensionTip.exeFriendlyName,
              windowsPath: extensionTip.windowsPath,
              whenNotInstalled
            });
          }
        }
      }
    }
    return result;
  }
};

// out-build/vs/platform/extensionManagement/node/extensionTipsService.js
var $Emc = class $Emc2 extends $Oic {
  constructor(environmentService, telemetryService, extensionManagementService, storageService, nativeHostService, extensionRecommendationNotificationService, fileService, productService) {
    super(environmentService.userHome, nativeHostService, telemetryService, extensionManagementService, storageService, extensionRecommendationNotificationService, fileService, productService);
  }
};
$Emc = __decorate([
  __param(0, $8i),
  __param(1, $tm),
  __param(2, $Jp),
  __param(3, $Dq),
  __param(4, $ykc),
  __param(5, $L_b),
  __param(6, $ul),
  __param(7, $Nk)
], $Emc);

// out-build/vs/platform/storage/common/storageService.js
var $Fmc = class extends $Fq {
  constructor(bb, cb, db, eb) {
    super();
    this.bb = bb;
    this.cb = cb;
    this.db = db;
    this.eb = eb;
    this.s = this.cb.defaultProfile;
    this.U = this.fb();
    this.W = this.cb.currentProfile;
    this.X = this.B(new $9c());
    this.Y = this.gb(this.W);
    this.Z = this.bb?.id;
    this.$ = this.B(new $9c());
    this.ab = this.hb(this.bb);
  }
  fb() {
    const storageDataBaseClient = this.B(new $cSb(this.db.getChannel("storage")));
    const applicationStorage = this.B(new $zq(storageDataBaseClient));
    this.B(applicationStorage.onDidChangeStorage((e) => this.u(-1, e)));
    return applicationStorage;
  }
  gb(profile) {
    this.X.clear();
    this.W = profile;
    let profileStorage;
    if ($Gq(profile)) {
      profileStorage = this.U;
    } else {
      const storageDataBaseClient = this.X.add(new $dSb(this.db.getChannel("storage"), profile));
      profileStorage = this.X.add(new $zq(storageDataBaseClient));
    }
    this.X.add(profileStorage.onDidChangeStorage((e) => this.u(0, e)));
    return profileStorage;
  }
  hb(workspace) {
    this.$.clear();
    this.Z = workspace?.id;
    let workspaceStorage = void 0;
    if (workspace) {
      const storageDataBaseClient = this.$.add(new $eSb(this.db.getChannel("storage"), workspace));
      workspaceStorage = this.$.add(new $zq(storageDataBaseClient));
      this.$.add(workspaceStorage.onDidChangeStorage((e) => this.u(1, e)));
    }
    return workspaceStorage;
  }
  async O() {
    await Promises.settled([
      this.U.init(),
      this.Y.init(),
      this.ab?.init() ?? Promise.resolve()
    ]);
  }
  P(scope) {
    switch (scope) {
      case -1:
        return this.U;
      case 0:
        return this.Y;
      default:
        return this.ab;
    }
  }
  Q(scope) {
    switch (scope) {
      case -1:
        return this.s.globalStorageHome.with({ scheme: Schemas.file }).fsPath;
      case 0:
        return this.W?.globalStorageHome.with({ scheme: Schemas.file }).fsPath;
      default:
        return this.Z ? `${$Ah(this.eb.workspaceStorageHome, this.Z, "state.vscdb").with({ scheme: Schemas.file }).fsPath}` : void 0;
    }
  }
  async close() {
    this.t();
    this.w(WillSaveStateReason.SHUTDOWN);
    await Promises.settled([
      this.U.close(),
      this.Y.close(),
      this.ab?.close() ?? Promise.resolve()
    ]);
  }
  async R(toProfile) {
    if (!this.M(this.W, toProfile)) {
      return;
    }
    const oldProfileStorage = this.Y;
    const oldItems = oldProfileStorage.items;
    if (oldProfileStorage !== this.U) {
      await oldProfileStorage.close();
    }
    this.Y = this.gb(toProfile);
    await this.Y.init();
    this.N(
      oldItems,
      this.Y,
      0
      /* StorageScope.PROFILE */
    );
  }
  async S(toWorkspace, preserveData) {
    const oldWorkspaceStorage = this.ab;
    const oldItems = oldWorkspaceStorage?.items ?? /* @__PURE__ */ new Map();
    await oldWorkspaceStorage?.close();
    this.ab = this.hb(toWorkspace);
    await this.ab.init();
    this.N(
      oldItems,
      this.ab,
      1
      /* StorageScope.WORKSPACE */
    );
  }
  hasScope(scope) {
    if ($6l(scope)) {
      return this.W.id === scope.id;
    }
    return this.Z === scope.id;
  }
};

// out-build/vs/platform/remote/node/nodeSocketFactory.js
import * as net3 from "net";

// out-build/vs/platform/remote/common/managedSocket.js
var $TCb = (path2, query, deubgLabel) => {
  const buffer = new Uint8Array(16);
  for (let i = 0; i < 16; i++) {
    buffer[i] = Math.round(Math.random() * 256);
  }
  const nonce = $of($7e.wrap(buffer));
  const headers = [
    `GET ws://localhost${path2}?${query}&skipWebSocketFrames=true HTTP/1.1`,
    `Connection: Upgrade`,
    `Upgrade: websocket`,
    `Sec-WebSocket-Key: ${nonce}`
  ];
  return headers.join("\r\n") + "\r\n\r\n";
};
var $UCb = $7e.fromString("\r\n\r\n");

// out-build/vs/platform/remote/node/nodeSocketFactory.js
var $Gmc = new class {
  supports(connectTo) {
    return true;
  }
  connect({ host, port }, path2, query, debugLabel) {
    return new Promise((resolve, reject) => {
      const socket = net3.createConnection({ host, port }, () => {
        socket.removeListener("error", reject);
        socket.write($TCb(path2, query, debugLabel));
        const onData = (data) => {
          const strData = data.toString();
          if (strData.indexOf("\r\n\r\n") >= 0) {
            socket.off("data", onData);
            resolve(new $Oi(socket, debugLabel));
          }
        };
        socket.on("data", onData);
      });
      socket.setNoDelay(true);
      socket.once("error", reject);
    });
  }
}();

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

// 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 os2 from "os";
import * as path from "path";
var module3 = { exports: {} };
(function() {
  const isESM = true;
  function factory(path2, os4, cwd2) {
    function getUserDataPath2(cliArgs, productName) {
      const userDataPath = doGetUserDataPath(cliArgs, productName);
      const pathsToResolve = [userDataPath];
      if (!path2.isAbsolute(userDataPath)) {
        pathsToResolve.unshift(cwd2);
      }
      return path2.resolve(...pathsToResolve);
    }
    function doGetUserDataPath(cliArgs, productName) {
      if (process.env["VSCODE_DEV"]) {
        productName = "code-oss-dev";
      }
      const portablePath = process.env["VSCODE_PORTABLE"];
      if (portablePath) {
        return path2.join(portablePath, "user-data");
      }
      let appDataPath = process.env["VSCODE_APPDATA"];
      if (appDataPath) {
        return path2.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 = path2.join(userProfile, "AppData", "Roaming");
          }
          break;
        case "darwin":
          appDataPath = path2.join(os4.homedir(), "Library", "Application Support");
          break;
        case "linux":
          appDataPath = process.env["XDG_CONFIG_HOME"] || path2.join(os4.homedir(), ".config");
          break;
        default:
          throw new Error("Platform not supported");
      }
      return path2.join(appDataPath, productName);
    }
    return {
      getUserDataPath: getUserDataPath2
    };
  }
  if (!isESM && typeof define === "function") {
    define(["path", "os", "vs/base/common/process"], function(path2, os4, process2) {
      return factory(path2, os4, process2.cwd());
    });
  } else if (typeof module3 === "object" && typeof module3.exports === "object") {
    module3.exports = factory(path, os2, process.env["VSCODE_CWD"] || process.cwd());
  } else {
    throw new Error("Unknown context");
  }
})();
var getUserDataPath = module3.exports.getUserDataPath;

// out-build/vs/platform/environment/node/environmentService.js
var $rn = class extends $on {
  constructor(args, productService) {
    super(args, {
      homeDir: homedir2(),
      tmpDir: tmpdir3(),
      userDataDir: getUserDataPath(args, productService.nameShort)
    }, productService);
  }
};

// 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 $Wkc = {
  request: "vscode:createSharedProcessRawConnection",
  response: "vscode:createSharedProcessRawConnectionResult"
};

// out-build/vs/base/node/osReleaseInfo.js
import { constants as FSConstants, promises as FSPromises } from "fs";
import { createInterface as readLines } from "readline";
async function $kh(errorLogger) {
  if ($m || $l) {
    return;
  }
  let handle2;
  for (const filePath of ["/etc/os-release", "/usr/lib/os-release", "/etc/lsb-release"]) {
    try {
      handle2 = await FSPromises.open(filePath, FSConstants.R_OK);
      break;
    } catch (err) {
    }
  }
  if (!handle2) {
    errorLogger("Unable to retrieve release information from known identifier paths.");
    return;
  }
  try {
    const osReleaseKeys = /* @__PURE__ */ new Set([
      "ID",
      "DISTRIB_ID",
      "ID_LIKE",
      "VERSION_ID",
      "DISTRIB_RELEASE"
    ]);
    const releaseInfo = {
      id: "unknown"
    };
    for await (const line of readLines({ input: handle2.createReadStream(), crlfDelay: Infinity })) {
      if (!line.includes("=")) {
        continue;
      }
      const key = line.split("=")[0].toUpperCase().trim();
      if (osReleaseKeys.has(key)) {
        const value = line.split("=")[1].replace(/"/g, "").toLowerCase().trim();
        if (key === "ID" || key === "DISTRIB_ID") {
          releaseInfo.id = value;
        } else if (key === "ID_LIKE") {
          releaseInfo.id_like = value;
        } else if (key === "VERSION_ID" || key === "DISTRIB_RELEASE") {
          releaseInfo.version_id = value;
        }
      }
    }
    return releaseInfo;
  } catch (err) {
    errorLogger(err);
  }
  return;
}

// out-build/vs/base/common/desktopEnvironmentInfo.js
var DesktopEnvironment;
(function(DesktopEnvironment2) {
  DesktopEnvironment2["UNKNOWN"] = "UNKNOWN";
  DesktopEnvironment2["CINNAMON"] = "CINNAMON";
  DesktopEnvironment2["DEEPIN"] = "DEEPIN";
  DesktopEnvironment2["GNOME"] = "GNOME";
  DesktopEnvironment2["KDE3"] = "KDE3";
  DesktopEnvironment2["KDE4"] = "KDE4";
  DesktopEnvironment2["KDE5"] = "KDE5";
  DesktopEnvironment2["KDE6"] = "KDE6";
  DesktopEnvironment2["PANTHEON"] = "PANTHEON";
  DesktopEnvironment2["UNITY"] = "UNITY";
  DesktopEnvironment2["XFCE"] = "XFCE";
  DesktopEnvironment2["UKUI"] = "UKUI";
  DesktopEnvironment2["LXQT"] = "LXQT";
})(DesktopEnvironment || (DesktopEnvironment = {}));
var kXdgCurrentDesktopEnvVar = "XDG_CURRENT_DESKTOP";
var kKDESessionEnvVar = "KDE_SESSION_VERSION";
function $wY() {
  const xdgCurrentDesktop = env[kXdgCurrentDesktopEnvVar];
  if (xdgCurrentDesktop) {
    const values = xdgCurrentDesktop.split(":").map((value) => value.trim()).filter((value) => value.length > 0);
    for (const value of values) {
      switch (value) {
        case "Unity": {
          const desktopSessionUnity = env["DESKTOP_SESSION"];
          if (desktopSessionUnity && desktopSessionUnity.includes("gnome-fallback")) {
            return DesktopEnvironment.GNOME;
          }
          return DesktopEnvironment.UNITY;
        }
        case "Deepin":
          return DesktopEnvironment.DEEPIN;
        case "GNOME":
          return DesktopEnvironment.GNOME;
        case "X-Cinnamon":
          return DesktopEnvironment.CINNAMON;
        case "KDE": {
          const kdeSession = env[kKDESessionEnvVar];
          if (kdeSession === "5") {
            return DesktopEnvironment.KDE5;
          }
          if (kdeSession === "6") {
            return DesktopEnvironment.KDE6;
          }
          return DesktopEnvironment.KDE4;
        }
        case "Pantheon":
          return DesktopEnvironment.PANTHEON;
        case "XFCE":
          return DesktopEnvironment.XFCE;
        case "UKUI":
          return DesktopEnvironment.UKUI;
        case "LXQt":
          return DesktopEnvironment.LXQT;
      }
    }
  }
  const desktopSession = env["DESKTOP_SESSION"];
  if (desktopSession) {
    switch (desktopSession) {
      case "deepin":
        return DesktopEnvironment.DEEPIN;
      case "gnome":
      case "mate":
        return DesktopEnvironment.GNOME;
      case "kde4":
      case "kde-plasma":
        return DesktopEnvironment.KDE4;
      case "kde":
        if (kKDESessionEnvVar in env) {
          return DesktopEnvironment.KDE4;
        }
        return DesktopEnvironment.KDE3;
      case "xfce":
      case "xubuntu":
        return DesktopEnvironment.XFCE;
      case "ukui":
        return DesktopEnvironment.UKUI;
    }
  }
  if ("GNOME_DESKTOP_SESSION_ID" in env) {
    return DesktopEnvironment.GNOME;
  }
  if ("KDE_FULL_SESSION" in env) {
    if (kKDESessionEnvVar in env) {
      return DesktopEnvironment.KDE4;
    }
    return DesktopEnvironment.KDE3;
  }
  return DesktopEnvironment.UNKNOWN;
}

// out-build/vs/base/node/osDisplayProtocolInfo.js
import { constants as FSConstants2, promises as FSPromises2 } from "fs";
var XDG_SESSION_TYPE = "XDG_SESSION_TYPE";
var WAYLAND_DISPLAY = "WAYLAND_DISPLAY";
var XDG_RUNTIME_DIR = "XDG_RUNTIME_DIR";
var DisplayProtocolType;
(function(DisplayProtocolType2) {
  DisplayProtocolType2["Wayland"] = "wayland";
  DisplayProtocolType2["XWayland"] = "xwayland";
  DisplayProtocolType2["X11"] = "x11";
  DisplayProtocolType2["Unknown"] = "unknown";
})(DisplayProtocolType || (DisplayProtocolType = {}));
async function $UY(errorLogger) {
  const xdgSessionType = env[XDG_SESSION_TYPE];
  if (xdgSessionType) {
    return xdgSessionType === "wayland" || xdgSessionType === "x11" ? xdgSessionType : "unknown";
  } else {
    const waylandDisplay = env[WAYLAND_DISPLAY];
    if (!waylandDisplay) {
      return "x11";
    } else {
      const xdgRuntimeDir = env[XDG_RUNTIME_DIR];
      if (!xdgRuntimeDir) {
        return "unknown";
      } else {
        const waylandServerPipe = $vc(xdgRuntimeDir, "wayland-0");
        try {
          await FSPromises2.access(waylandServerPipe, FSConstants2.R_OK);
          return "wayland";
        } catch (err) {
          errorLogger(err);
          return "unknown";
        }
      }
    }
  }
}
function $VY(displayProtocol, ozonePlatform) {
  if (!ozonePlatform) {
    return displayProtocol === "wayland" ? "xwayland" : "x11";
  } else {
    switch (ozonePlatform) {
      case "auto":
        return displayProtocol;
      case "x11":
        return displayProtocol === "wayland" ? "xwayland" : "x11";
      case "wayland":
        return "wayland";
      default:
        return "unknown";
    }
  }
}

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

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

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

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

// out-build/vs/base/node/powershell.js
import * as os3 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(os3.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/shell.js
async function $Um(os4, env2) {
  if (os4 === 1) {
    if ($l) {
      return getSystemShellWindows();
    }
    return $Sm(env2);
  }
  return getSystemShellUnixLike(os4, env2);
}
var _TERMINAL_DEFAULT_SHELL_UNIX_LIKE = null;
function getSystemShellUnixLike(os4, env2) {
  if ($n && os4 === 2 || $m && os4 === 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/platform/environment/node/argvHelper.js
import assert from "assert";

// 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 $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
};

// out-build/vs/platform/environment/node/argvHelper.js
function $5m(env2) {
  return env2["VSCODE_CLI"] === "1";
}

// 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 (resolve, 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 {
          resolve(await doResolveUnixShellEnv(logService, cts.token));
        } catch (error) {
          if (!$eb(error) && !cts.token.isCancellationRequested) {
            reject(new Error(localize(2079, null, $Kj(error))));
          } else {
            resolve({});
          }
        } 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((resolve, 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 = spawn2(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", (code, 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 (code || signal) {
        return reject(new Error(localize(2080, null, code, 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);
        resolve(env3);
      } catch (err) {
        logService.error("getUnixShellEnvironment#errorCaught", $Kj(err));
        reject(err);
      }
    });
  });
}

// 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 module4 = endpoint.protocol === "https:" ? await import("https") : await import("http");
  return module4.request;
}
async function $Cs(options, token) {
  return Promises.withAsyncBody(async (resolve, 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(resolve, reject);
      } else {
        let stream = res;
        if (!options.isChromiumNetwork && res.headers["content-encoding"] === "gzip") {
          stream = res.pipe(createGunzip());
        }
        resolve({ 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 net4.request;
}
var $Vlc = class extends $Bs {
  request(options, token) {
    return super.request({ ...options || {}, getRawRequest, isChromiumNetwork: true }, token);
  }
};

// out-build/vs/code/electron-utility/sharedProcess/sharedProcessMain.js
var SharedProcessMain = class extends $0c {
  constructor(f) {
    super();
    this.f = f;
    this.a = this.B(new $aZ(this));
    this.b = void 0;
    this.c = this.B(new $De());
    this.g();
  }
  g() {
    let didExit = false;
    const onExit = () => {
      if (!didExit) {
        didExit = true;
        this.b?.fireOnWillShutdown();
        this.dispose();
      }
    };
    process.once("exit", onExit);
    $bZ(process.parentPort, $Ukc.exit, onExit);
  }
  async init() {
    const instantiationService = await this.h();
    $Grb();
    instantiationService.invokeFunction((accessor) => {
      const logService = accessor.get($uk);
      const telemetryService = accessor.get($tm);
      const userDataProfilesService = accessor.get($7l);
      logService.trace("sharedProcess configuration", JSON.stringify(this.f));
      this.j(accessor);
      this.m(logService);
      this.n(telemetryService, userDataProfilesService);
      this.B(userDataProfilesService.onDidChangeProfiles(() => this.n(telemetryService, userDataProfilesService)));
      this.r(telemetryService, logService);
    });
    this.B($7c(instantiationService.createInstance($9lc, this.f.codeCachePath), instantiationService.createInstance($0lc), instantiationService.createInstance($amc), instantiationService.createInstance($_lc), instantiationService.createInstance($$lc), instantiationService.createInstance($xmc), instantiationService.createInstance($pmc)));
  }
  async h() {
    const services = new $Xi();
    const productService = { _serviceBrand: void 0, ...product_default };
    services.set($Nk, productService);
    const mainRouter = new $Hi((ctx) => ctx === "main");
    const mainProcessService = new $IOb(this.a, mainRouter);
    services.set($HOb, mainProcessService);
    const policyService = this.f.policiesData ? new $llc(this.f.policiesData, mainProcessService.getChannel("policy")) : new $Qo();
    services.set($Oo, policyService);
    const environmentService = new $rn(this.f.args, productService);
    services.set($8i, environmentService);
    const loggerService = new $Ps(void 0, this.f.logLevel, environmentService.logsHome, this.f.loggers.map((loggerResource) => ({ ...loggerResource, resource: URI.revive(loggerResource.resource) })), mainProcessService.getChannel("logger"));
    services.set($vk, loggerService);
    const logger = this.B(loggerService.createLogger("sharedprocess", { name: localize(172, null) }));
    const consoleLogger = this.B(new $Ck(logger.getLevel()));
    const logService = this.B(new $JS(logger, [consoleLogger]));
    services.set($uk, logService);
    this.b = this.B(new $zmc(logService));
    services.set($ymc, this.b);
    const fileService = this.B(new $mr(logService));
    services.set($ul, fileService);
    const diskFileSystemProvider = this.B(new $Pr(logService));
    fileService.registerProvider(Schemas.file, diskFileSystemProvider);
    const uriIdentityService = new $et(fileService);
    services.set($5l, uriIdentityService);
    const userDataProfilesService = this.B(new $QS(this.f.profiles.all, URI.revive(this.f.profiles.home).with({ scheme: environmentService.userRoamingDataHome.scheme }), mainProcessService.getChannel("userDataProfiles")));
    services.set($7l, userDataProfilesService);
    const userDataFileSystemProvider = this.B(new $Zlc(
      Schemas.file,
      // Specifically for user data, use the disk file system provider
      // from the main process to enable atomic read/write operations.
      // Since user data can change very frequently across multiple
      // processes, we want a single process handling these operations.
      this.B(new $sS(mainProcessService.getChannel($rS), { pathCaseSensitive: $n })),
      Schemas.vscodeUserData,
      userDataProfilesService,
      uriIdentityService,
      logService
    ));
    fileService.registerProvider(Schemas.vscodeUserData, userDataFileSystemProvider);
    const configurationService = this.B(new $gp(userDataProfilesService.defaultProfile.settingsResource, fileService, policyService, logService));
    services.set($tj, configurationService);
    const storageService = new $Fmc(void 0, { defaultProfile: userDataProfilesService.defaultProfile, currentProfile: userDataProfilesService.defaultProfile }, mainProcessService, environmentService);
    services.set($Dq, storageService);
    this.B($8c(() => storageService.flush()));
    await Promise.all([
      configurationService.initialize(),
      storageService.initialize()
    ]);
    const requestService = new $Vlc(configurationService, environmentService, logService);
    services.set($qq, requestService);
    services.set($bmc, new $Wi(
      $cmc,
      void 0,
      false
      /* proxied to other processes */
    ));
    services.set($GH, new $Wi(
      $omc,
      void 0,
      false
      /* proxied to other processes */
    ));
    const nativeHostService = new $2lc(-1, mainProcessService);
    services.set($ykc, nativeHostService);
    services.set($kp, new $Wi($1S, void 0, true));
    const activeWindowManager = this.B(new $ilc(nativeHostService));
    const activeWindowRouter = new $Hi((ctx) => activeWindowManager.getActiveClientId().then((id2) => ctx === id2));
    services.set($L_b, new $Bmc(this.a.getChannel("extensionRecommendationNotification", activeWindowRouter)));
    let telemetryService;
    const appenders = [];
    const internalTelemetry = $5p(productService, configurationService);
    if ($Zp(productService, environmentService)) {
      const logAppender = new $bic(logService, loggerService, environmentService, productService);
      appenders.push(logAppender);
      if (!$1p(productService, environmentService) && productService.aiConfig?.ariaKey) {
        const collectorAppender = new $xS(requestService, internalTelemetry, "monacoworkbench", null, productService.aiConfig.ariaKey);
        this.B($8c(() => collectorAppender.flush()));
        appenders.push(collectorAppender);
      }
      telemetryService = new $Ds({
        appenders,
        commonProperties: $Qp(release3(), hostname2(), process.arch, productService.commit, productService.version, this.f.machineId, this.f.sqmId, this.f.devDeviceId, internalTelemetry),
        sendErrorTelemetry: true,
        piiPaths: $6p(environmentService)
      }, configurationService, productService);
    } else {
      telemetryService = $Up;
      const nullAppender = $Yp;
      appenders.push(nullAppender);
    }
    this.a.registerChannel("telemetryAppender", new $Zkc(appenders));
    services.set($tm, telemetryService);
    const customEndpointTelemetryService = new $dmc(configurationService, telemetryService, logService, loggerService, environmentService, productService);
    services.set($um, customEndpointTelemetryService);
    services.set($6q, new $Wi($IS, void 0, true));
    services.set($0q, new $Wi($mlc, void 0, true));
    if (productService.quality === "stable") {
      services.set($Qq, new $Wi($Rq, void 0, true));
    } else {
      services.set($Qq, ProxyChannel.toService(mainProcessService.getChannel("signatureVerificationService")));
    }
    services.set($ir, new $Wi($jr, void 0, true));
    services.set($Gp, new $Wi($Mq, void 0, true));
    services.set($Np, new $Wi(
      $Emc,
      void 0,
      false
      /* Eagerly scans and computes exe based recommendations */
    ));
    services.set($vs, new $Wi(
      $xs,
      void 0,
      false
      /* proxied to other processes */
    ));
    services.set($bn, new $Wi(
      $lt,
      void 0,
      false
      /* proxied to other processes */
    ));
    services.set($GRb, new $Wi($HRb, void 0, true));
    services.set($2rb, new $Wi($cUb, void 0, true));
    services.set($1rb, ProxyChannel.toService(this.a.getChannel("userDataSyncUtil", (client) => client.ctx !== "main")));
    services.set($Mp, new $Wi(
      $ERb,
      void 0,
      false
      /* Eagerly resets installed extensions */
    ));
    services.set($aUb, new $Wi($bUb, void 0, true));
    services.set($Yw, new $Wi($Zw));
    services.set($Lrb, new $Wi($bTb, void 0, true));
    services.set($Mrb, new $Wi($dTb, void 0, true));
    services.set($yrb, new $Wi($Arb, void 0, true));
    services.set($Nrb, new $Wi(
      $Qic,
      void 0,
      false
      /* Eagerly cleans up old backups */
    ));
    services.set($Wrb, new $Wi($Fic, void 0, true));
    services.set($Xrb, new $Wi(
      $Vic,
      void 0,
      false
      /* Initializes the Sync State */
    ));
    services.set($gSb, new $Wi($kmc, void 0, true));
    services.set($Yrb, new $Wi($Ajc, void 0, true));
    services.set($hm, new $Wi(
      $Wlc,
      void 0,
      false
      /* proxied to other processes */
    ));
    const remoteSocketFactoryService = new $fm();
    services.set($em, remoteSocketFactoryService);
    remoteSocketFactoryService.register(0, $Gmc);
    services.set($bx, new $Wi($Ulc));
    services.set($lmc, new $Wi($nmc));
    services.set($qmc, new $Wi($Amc));
    return new $Sr(services);
  }
  j(accessor) {
    const channel = new $Tq(accessor.get($Jp), () => null);
    this.a.registerChannel("extensions", channel);
    const languagePacksChannel = ProxyChannel.fromService(accessor.get($vs), this.q);
    this.a.registerChannel("languagePacks", languagePacksChannel);
    const diagnosticsChannel = ProxyChannel.fromService(accessor.get($bn), this.q);
    this.a.registerChannel("diagnostics", diagnosticsChannel);
    const extensionTipsChannel = new $Vq(accessor.get($Np));
    this.a.registerChannel("extensionTipsService", extensionTipsChannel);
    const checksumChannel = ProxyChannel.fromService(accessor.get($bmc), this.q);
    this.a.registerChannel("checksum", checksumChannel);
    const profilingChannel = ProxyChannel.fromService(accessor.get($GH), this.q);
    this.a.registerChannel("v8InspectProfiling", profilingChannel);
    const userDataSyncMachineChannel = ProxyChannel.fromService(accessor.get($yrb), this.q);
    this.a.registerChannel("userDataSyncMachines", userDataSyncMachineChannel);
    const customEndpointTelemetryChannel = ProxyChannel.fromService(accessor.get($um), this.q);
    this.a.registerChannel("customEndpointTelemetry", customEndpointTelemetryChannel);
    const userDataSyncAccountChannel = new $emc(accessor.get($GRb));
    this.a.registerChannel("userDataSyncAccount", userDataSyncAccountChannel);
    const userDataSyncStoreManagementChannel = new $gmc(accessor.get($Lrb));
    this.a.registerChannel("userDataSyncStoreManagement", userDataSyncStoreManagementChannel);
    const userDataSyncChannel = new $imc(accessor.get($Xrb), accessor.get($7l), accessor.get($uk));
    this.a.registerChannel("userDataSync", userDataSyncChannel);
    const userDataAutoSync = this.B(accessor.get($Yi).createInstance($Dmc));
    this.a.registerChannel("userDataAutoSync", ProxyChannel.fromService(userDataAutoSync, this.q));
    this.a.registerChannel("IUserDataSyncResourceProviderService", ProxyChannel.fromService(accessor.get($Yrb), this.q));
    const sharedProcessTunnelChannel = ProxyChannel.fromService(accessor.get($lmc), this.q);
    this.a.registerChannel($mmc, sharedProcessTunnelChannel);
    const remoteTunnelChannel = ProxyChannel.fromService(accessor.get($qmc), this.q);
    this.a.registerChannel("remoteTunnel", remoteTunnelChannel);
  }
  m(logService) {
    process.on("uncaughtException", (error) => $ab(error));
    process.on("unhandledRejection", (reason) => $ab(reason));
    setUnexpectedErrorHandler((error) => {
      const message = $Kj(error, true);
      if (!message) {
        return;
      }
      logService.error(`[uncaught exception in sharedProcess]: ${message}`);
    });
  }
  n(telemetryService, userDataProfilesService) {
    telemetryService.publicLog2("profilesInfo", {
      count: userDataProfilesService.profiles.length
    });
  }
  async r(telemetryService, logService) {
    if ($n) {
      const [releaseInfo, displayProtocol] = await Promise.all([
        $kh(logService.error.bind(logService)),
        $UY(logService.error.bind(logService))
      ]);
      const desktopEnvironment = $wY();
      const codeSessionType = $VY(displayProtocol, this.f.args["ozone-platform"]);
      if (releaseInfo) {
        telemetryService.publicLog2("clientPlatformInfo", {
          platformId: releaseInfo.id,
          platformVersionId: releaseInfo.version_id,
          platformIdLike: releaseInfo.id_like,
          desktopEnvironment,
          displayProtocol,
          codeDisplayProtocol: codeSessionType
        });
      }
    }
  }
  handledClientConnection(e) {
    if (e.data !== $Wkc.response) {
      return false;
    }
    const port = e.ports.at(0);
    if (port) {
      this.c.fire(port);
      return true;
    }
    return false;
  }
};
async function main(configuration) {
  try {
    const sharedProcess = new SharedProcessMain(configuration);
    process.parentPort.postMessage($Ukc.ipcReady);
    await sharedProcess.init();
    process.parentPort.postMessage($Ukc.initDone);
  } catch (error) {
    process.parentPort.postMessage({ error: error.toString() });
  }
}
var handle = setTimeout(() => {
  process.parentPort.postMessage({ warning: "[SharedProcess] did not receive configuration within 30s..." });
}, 3e4);
process.parentPort.once("message", (e) => {
  clearTimeout(handle);
  main(e.data);
});
export {
  main
};

//# sourceMappingURL=sharedProcessMain.js.map
